java动态代理源码分析
时间: 2023-09-13 15:11:27 浏览: 111
Java动态代理是一种在运行时生成代理类的机制,用于代替手动编写代理类的过程。在Java中,动态代理通常使用JDK自带的Proxy和InvocationHandler接口来实现。
下面是一个简单的动态代理示例:
```java
public interface UserService {
void save();
}
public class UserServiceImpl implements UserService {
public void save() {
System.out.println("保存用户");
}
}
public class UserInvocationHandler implements InvocationHandler {
private Object target;
public UserInvocationHandler(Object target) {
this.target = target;
}
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("开始操作");
Object result = method.invoke(target, args);
System.out.println("操作完成");
return result;
}
}
public class Main {
public static void main(String[] args) {
UserService userService = new UserServiceImpl();
UserService proxy = (UserService) Proxy.newProxyInstance(userService.getClass().getClassLoader(),
userService.getClass().getInterfaces(), new UserInvocationHandler(userService));
proxy.save();
}
}
```
在这个示例中,我们首先定义了一个UserService接口和一个UserServiceImpl实现类。然后我们定义了一个UserInvocationHandler类,它实现了InvocationHandler接口,该接口中只有一个invoke方法,该方法用于在代理对象上调用方法时执行的代码逻辑。在Main类中,我们通过Proxy.newProxyInstance方法创建了一个代理对象proxy,并将其强制转换为UserService类型。该方法需要三个参数:ClassLoader,该代理对象实现的接口列表和InvocationHandler实例。最后,我们通过代理对象调用了save方法。
下面是动态代理的源码分析:
在Proxy.newProxyInstance方法中,我们可以看到它调用了Proxy.getProxyClass方法,该方法用于获取代理类的Class对象。
```java
public static Object newProxyInstance(ClassLoader loader,
Class<?>[] interfaces,
InvocationHandler h)
throws IllegalArgumentException
{
Objects.requireNonNull(h);
final Class<?>[] intfs = interfaces.clone();
final SecurityManager sm = System.getSecurityManager();
if (sm != null) {
checkProxyAccess(Reflection.getCallerClass(), loader, intfs);
}
/*
* Look up or generate the designated proxy class.
*/
Class<?> cl = getProxyClass0(loader, intfs);
/*
* Invoke its constructor with the designated invocation handler.
*/
try {
if (sm != null) {
checkNewProxyPermission(Reflection.getCallerClass(), cl);
}
final Constructor<?> cons = cl.getConstructor(constructorParams);
final InvocationHandler ih = h;
if (!Modifier.isPublic(cl.getModifiers())) {
AccessController.doPrivileged(new PrivilegedAction<Void>() {
public Void run() {
cons.setAccessible(true);
return null;
}
});
}
return cons.newInstance(new Object[]{h});
} catch (NoSuchMethodException e) {
throw new InternalError(e.toString());
} catch (IllegalAccessException e) {
throw new InternalError(e.toString());
} catch (InstantiationException e) {
throw new InternalError(e.toString());
} catch (InvocationTargetException e) {
Throwable t = e.getCause();
if (t instanceof RuntimeException) {
throw (RuntimeException) t;
} else {
throw new InternalError(t.toString());
}
}
}
```
在getProxyClass0方法中,它会先尝试从缓存中获取代理类,如果没有找到则调用ProxyClassFactory的apply方法生成代理类。
```java
private static Class<?> getProxyClass0(ClassLoader loader,
Class<?>... interfaces) {
if (interfaces.length > 65535) {
throw new IllegalArgumentException("interface limit exceeded");
}
// If the proxy class defined by the given loader implementing
// the given interfaces exists, this will simply return the cached copy;
// otherwise, it will create the proxy class via the ProxyClassFactory
return proxyClassCache.get(loader, interfaces);
}
```
在ProxyClassFactory的apply方法中,它会使用ASM框架生成代理类的字节码。ASM是一个轻量级的Java字节码操作和分析框架,可以用于动态生成字节码。
```java
public Class<?> apply(ClassLoader loader, Class<?>[] interfaces) {
Map<Class<?>, Boolean> interfaceSet = new IdentityHashMap<>(interfaces.length);
for (Class<?> intf : interfaces) {
/*
* Verify that the class loader resolves the name of this
* interface to the same Class object.
*/
Class<?> interfaceClass = null;
try {
interfaceClass = Class.forName(intf.getName(), false, loader);
} catch (ClassNotFoundException e) {
}
if (interfaceClass != intf) {
throw new IllegalArgumentException(
intf + " is not visible from class loader");
}
/*
* Verify that the interface is a true interface
*/
if (!interfaceClass.isInterface()) {
throw new IllegalArgumentException(
interfaceClass.getName() + " is not an interface");
}
/*
* Verify that this interface is not a duplicate.
*/
if (interfaceSet.put(interfaceClass, Boolean.TRUE) != null) {
throw new IllegalArgumentException(
"repeated interface: " + interfaceClass.getName());
}
}
/*
* Choose a name for the proxy class to generate.
*/
String proxyName = generateProxyName(interfaces);
/*
* Generate the specified proxy class.
*/
byte[] proxyClassFile = ProxyGenerator.generateProxyClass(
proxyName, interfaces, accessFlags);
try {
return defineClass0(loader, proxyName,
proxyClassFile, 0, proxyClassFile.length);
} catch (ClassFormatError e) {
/*
* A ClassFormatError here means that (barring bugs in the
* proxy class generation code) there was some other
* invalid aspect of the arguments supplied to the proxy
* class creation (such as virtual machine limitations
* exceeded).
*/
throw new IllegalArgumentException(e.toString());
}
}
```
在ProxyGenerator.generateProxyClass方法中,它使用ASM框架生成代理类的字节码。
```java
public static byte[] generateProxyClass(String var0, Class<?>[] var1, int var2) {
return generateProxyClass(var0, var1, null, var2);
}
public static byte[] generateProxyClass(String var0, Class<?>[] var1, Class<?> var2, int var3) {
ProxyGenerator var4 = new ProxyGenerator(var0, var1, var2, var3);
byte[] var5 = var4.generateClassFile();
if (DUMP_CLASS) {
dumpClass(var0, var5);
}
return var5;
}
```
在ProxyGenerator的generateClassFile方法中,它使用ASM框架生成代理类的字节码。
```java
public byte[] generateClassFile() {
this.createClassInfo();
this.createFieldInfo();
this.createConstructorInfo();
this.createMethodInfo();
this.createAttributeInfo();
return this.classWriter.toByteArray();
}
```
总体来说,Java动态代理实现的核心在于使用ASM框架生成代理类的字节码。ASM框架提供了一种轻量级的生成和修改Java字节码的方式,可以很方便地生成符合Java规范的字节码。通过动态生成代理类,我们可以省去手动编写代理类的繁琐过程,并且可以使代理类更加灵活和易于维护。
阅读全文