Java的动态代理,从使用上和原理上分析,我认为其实可以当成一个单独的框架,因此把本文归为框架分析中。一句话说动态代理的功能的话,我认为是 通过生成代码的方式实现对接口的代理,常用于框架开发中。如Retrofit
1、Proxy.newProxyInstance()的实现
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.
*/
//这里传ClassLoader和接口,生成了Class
Class<?> cl = getProxyClass0(loader, intfs);
/*
* Invoke its constructor with the designated invocation handler.
*/
try {
if (sm != null) {
checkNewProxyPermission(Reflection.getCallerClass(), cl);
}
//获取Class的构造方法,注意这里的参数类型是InvocationHandler
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;
}
});
}
//构造实例,将InvocationHandler实例传入
return cons.newInstance(new Object[]{h});
} catch (IllegalAccessException|InstantiationException e) {
throw new InternalError(e.toString(), e);
} catch (InvocationTargetException e) {
Throwable t = e.getCause();
if (t instanceof RuntimeException) {
throw (RuntimeException) t;
} else {
throw new InternalError(t.toString(), t);
}
} catch (NoSuchMethodException e) {
throw new InternalError(e.toString(), e);
}
}
2、getProxyClass0如何生成Class
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
// 这里的proxyClassCache只是个缓存,实际上生成操作是在ProxyClassFactory类
// proxyClassCache是 proxyClassCache = new WeakCache<>(new KeyFactory(), new ProxyClassFactory());
return proxyClassCache.get(loader, interfaces);
}
3、查看ProxyClassFactory类代码
注意:WeakCache获取实例是通过apply方法,所以查看ProxyClassFactory的apply方法
public Class<?> apply(ClassLoader loader, Class<?>[] interfaces) {
/**
* 下面显示根据interfaces的名称加载各个interface,并判断确实是interface,而不是类,如果是类会抛出异常
*/
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");
}
/*
* 这里判断了传进来的class必须是接口,而不能是class
* Verify that the Class object actually represents an
* interface.
*/
if (!interfaceClass.isInterface()) {
throw new IllegalArgumentException(
interfaceClass.getName() + " is not an interface");
}
/*
* 不能传两个相同的interface
* Verify that this interface is not a duplicate.
*/
if (interfaceSet.put(interfaceClass, Boolean.TRUE) != null) {
throw new IllegalArgumentException(
"repeated interface: " + interfaceClass.getName());
}
}
String proxyPkg = null; // package to define proxy class in
// 动态代理默认生成的类是Public Final修饰的
int accessFlags = Modifier.PUBLIC | Modifier.FINAL;
/*
* Record the package of a non-public proxy interface so that the
* proxy class will be defined in the same package. Verify that
* all non-public proxy interfaces are in the same package.
* 接口如果不是public,则生成的类的包名用该类的包名。
* 如果接口不止一个不是public,并且又不在同一个包名下,则抛出异常~,因为一定会有interface访问不到
*/
for (Class<?> intf : interfaces) {
int flags = intf.getModifiers();
if (!Modifier.isPublic(flags)) {
accessFlags = Modifier.FINAL;
String name = intf.getName();
int n = name.lastIndexOf('.');
String pkg = ((n == -1) ? "" : name.substring(0, n + 1));
if (proxyPkg == null) {
proxyPkg = pkg;
} else if (!pkg.equals(proxyPkg)) {
throw new IllegalArgumentException(
"non-public interfaces from different packages");
}
}
}
//如果接口都是public的,则会使用默认包名com.sun.proxy
if (proxyPkg == null) {
// if no non-public proxy interfaces, use com.sun.proxy package
proxyPkg = ReflectUtil.PROXY_PACKAGE + ".";
}
/*
* nextUniqueNumber是个静态成员,为了做到每次加一
* Choose a name for the proxy class to generate.
*/
long num = nextUniqueNumber.getAndIncrement();
// 包名.$ProxyN 这里的N是每次加1的
String proxyName = proxyPkg + proxyClassNamePrefix + num;
/*
* 根据类名,实现的接口名称,修饰符生成class的字节码
* Generate the specified proxy class.
*/
byte[] proxyClassFile = ProxyGenerator.generateProxyClass(
proxyName, interfaces, accessFlags);
try {
//根据字节码加载class
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());
}
}
}
总结步骤:
1、根据参数中传过来的interface的名称,加载interface
2、校验interface确实是Interface,而不是class
3、根据interface是否是public,校验并生成将要生成的类的包名。规则:
3.1、接口如果只有一个不是public,则生成的类的包名用该类的包名。
3.2、如果接口不止一个不是public,并且又不在同一个包名下,则抛出异常~,因为一定会有interface访问不到
3.3、如果接口全都是public,则使用默认包名com.sun.proxy
4、生成的类名由为包名.$proxyN, 其中N每生成一个类加1
5、使用ProxyGenerator.generateProxyClass根据类名,实现接口名,修饰符生成字节码
6、加载字节码,返回class,这一步看源码是个native方法,暂不深究。
4、分析ProxyGenerator.generateProxyClass生成的class内容
4.1、这里ProxyGenerator的源码非常长,此处不分析源码。而通过生成一个class,分析class的内容来探索
//IHello接口代码
public interface IHello {
void hello();
}
//生成class的测试代码如下:
public static void main(String[] args) {
byte[] helloClassBytes = ProxyGenerator.generateProxyClass("MyProxy", new Class[]{IHello.class}, Modifier.PUBLIC | Modifier.FINAL);
FilesKt.writeBytes(new File("MyProxy.class"), helloClassBytes);
}
4.2、分析MyProxy.class
public final class MyProxy extends Proxy implements IHello {
private static Method m1;
private static Method m3;
private static Method m2;
private static Method m0;
//构造方法传入的参数是InvacationHandler,对应上文说的获取参数为InvacationHandler的构造函数
public MyProxy(InvocationHandler var1) throws {
super(var1);
}
public final boolean equals(Object var1) throws {
try {
return (Boolean)super.h.invoke(this, m1, new Object[]{var1});
} catch (RuntimeException | Error var3) {
throw var3;
} catch (Throwable var4) {
throw new UndeclaredThrowableException(var4);
}
}
public final void hello() throws {
try {
super.h.invoke(this, m3, (Object[])null);
} catch (RuntimeException | Error var2) {
throw var2;
} catch (Throwable var3) {
throw new UndeclaredThrowableException(var3);
}
}
public final String toString() throws {
try {
return (String)super.h.invoke(this, m2, (Object[])null);
} catch (RuntimeException | Error var2) {
throw var2;
} catch (Throwable var3) {
throw new UndeclaredThrowableException(var3);
}
}
public final int hashCode() throws {
try {
return (Integer)super.h.invoke(this, m0, (Object[])null);
} catch (RuntimeException | Error var2) {
throw var2;
} catch (Throwable var3) {
throw new UndeclaredThrowableException(var3);
}
}
// 为m1,m2,m3,m0等method赋值
static {
try {
m1 = Class.forName("java.lang.Object").getMethod("equals", Class.forName("java.lang.Object"));
m3 = Class.forName("com.breeze.test.IHello").getMethod("hello");
m2 = Class.forName("java.lang.Object").getMethod("toString");
m0 = Class.forName("java.lang.Object").getMethod("hashCode");
} catch (NoSuchMethodException var2) {
throw new NoSuchMethodError(var2.getMessage());
} catch (ClassNotFoundException var3) {
throw new NoClassDefFoundError(var3.getMessage());
}
}
}
可以看到实际上所有的方法走的都是h.invoke,那么h是什么呢?看Proxy类
protected Proxy(InvocationHandler h) {
Objects.requireNonNull(h);
this.h = h;
}
到此便分析清楚了,h就是Proxy.newProxyInstance方法传入的InvacationHandler。所有方法执行时都走的是InvacationHandler的invoke方法。
//这里的proxy就是生成的实例,method是代理的方法,args是透传的参数
//常见使用动态代理的错误写法:在invoke中写method.invoke(proxy,args)。这样写后调用proxy的method会造成死循环
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable;
5、动态代理拓展
从上面的讲述中可得知,java自带的动态代理只能代理接口,如果想生成类的代理,会抛出异常。这时可以使用CgLib来实现。具体此处不讲述,API实际上和java的动态代理类似,原理其实也是一样的,生成字节码后加载。