如下List-1,动态代理生成的object是代理类,List-1的执行结果是List-2所示
List-1
1ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); 2Object object = Proxy.newProxyInstance(classLoader, new Class[]{EchoService.class}, new InvocationHandler() { 3 @Override 4 public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { 5 if (EchoService.class.isAssignableFrom(method.getDeclaringClass())) { 6 return new StaticProxyEchoService(new DefaultEchoServiceImpl()).echo((String) args[0]); 7 } 8 return null; 9 } 10}); 11EchoService echoService = (EchoService) object; 12echoService.echo("Hello world"); 13LOG.info(object.getClass().getSuperclass() == Proxy.class); 14Class<?>[] interfaces = object.getClass().getInterfaces(); 15LOG.info(interfaces.length == 1); 16LOG.info(interfaces[0] == EchoService.class); 17Constructor<?>[] constructors = object.getClass().getConstructors(); 18LOG.info(constructors.length == 1); 19LOG.info(constructors[0].getParameterCount() == 1); 20LOG.info(constructors[0].getParameterTypes()[0] == InvocationHandler.class);
List-2
12020-12-22 21:13:46.617 [main] INFO com.mjduan.project.log.LOG info() 27 用时:0 22020-12-22 21:13:46.622 [main] INFO com.mjduan.project.log.LOG info() 27 true 32020-12-22 21:13:46.622 [main] INFO com.mjduan.project.log.LOG info() 27 true 42020-12-22 21:13:46.622 [main] INFO com.mjduan.project.log.LOG info() 27 true 52020-12-22 21:13:46.622 [main] INFO com.mjduan.project.log.LOG info() 27 true 62020-12-22 21:13:46.623 [main] INFO com.mjduan.project.log.LOG info() 27 true 72020-12-22 21:13:46.623 [main] INFO com.mjduan.project.log.LOG info() 27 true
我们可以知道object.getClass的类结构大概是如下List-3
List-3
1class $Proxy0 extends Proxy implements EchoService{ 2 3 $Proxy0(InvocationHandler handler){ 4 super(handler); 5 } 6 7}
即动态生成的类object继承了Proxy,同时实现了EchoService接口,为什么继承要继承Proxy,这是因为我们自定义的InvocationHandler类实现时赋值给Proxy的属性的,如下List-4是Proxy的构造方法
List-4
1protected InvocationHandler h; 2 3private Proxy() { 4} 5 6protected Proxy(InvocationHandler h) { 7 Objects.requireNonNull(h); 8 this.h = h; 9}
Proxy.newProxyInstance()的时候,如下List-5所示
1处要对传入的interfaces进行clone(),因为是数组,会被修改
2处是重点,是具体生成$Proxy的class的地方
3处获取$Proxy的构造方法,使用反射实例化
List-5
1public static Object newProxyInstance(ClassLoader loader, 2 Class<?>[] interfaces, 3 InvocationHandler h) 4 throws IllegalArgumentException 5{ 6 Objects.requireNonNull(h); 7 8 final Class<?>[] intfs = interfaces.clone();//1 9 final SecurityManager sm = System.getSecurityManager(); 10 if (sm != null) { 11 checkProxyAccess(Reflection.getCallerClass(), loader, intfs); 12 } 13 14 /* 15 * Look up or generate the designated proxy class. 16 */ 17 Class<?> cl = getProxyClass0(loader, intfs);//2 18 19 /* 20 * Invoke its constructor with the designated invocation handler. 21 */ 22 try { 23 if (sm != null) { 24 checkNewProxyPermission(Reflection.getCallerClass(), cl); 25 } 26 27 final Constructor<?> cons = cl.getConstructor(constructorParams);//3 28 final InvocationHandler ih = h; 29 if (!Modifier.isPublic(cl.getModifiers())) { 30 AccessController.doPrivileged(new PrivilegedAction<Void>() { 31 public Void run() { 32 cons.setAccessible(true); 33 return null; 34 } 35 }); 36 } 37 return cons.newInstance(new Object[]{h});//4 38 } catch (IllegalAccessException|InstantiationException e) { 39 throw new InternalError(e.toString(), e); 40 } catch (InvocationTargetException e) { 41 Throwable t = e.getCause(); 42 if (t instanceof RuntimeException) { 43 throw (RuntimeException) t; 44 } else { 45 throw new InternalError(t.toString(), t); 46 } 47 } catch (NoSuchMethodException e) { 48 throw new InternalError(e.toString(), e); 49 } 50}
Proxy的getProxyClass0方法如下List-6,通过WeakCache来生成class类,
List-6
1private static Class<?> getProxyClass0(ClassLoader loader, 2 Class<?>... interfaces) { 3 if (interfaces.length > 65535) { 4 throw new IllegalArgumentException("interface limit exceeded"); 5 } 6 7 // If the proxy class defined by the given loader implementing 8 // the given interfaces exists, this will simply return the cached copy; 9 // otherwise, it will create the proxy class via the ProxyClassFactory 10 return proxyClassCache.get(loader, interfaces); 11}
proxyClassCache的定义如下List-7所示,ProxyClassFactory是生成动态代理类的工厂
List-7
1public class Proxy implements java.io.Serializable { 2 3 private static final long serialVersionUID = -2222568056686623797L; 4 5 /** parameter types of a proxy class constructor */ 6 private static final Class<?>[] constructorParams = 7 { InvocationHandler.class }; 8 9 private static final WeakCache<ClassLoader, Class<?>[], Class<?>> 10 proxyClassCache = new WeakCache<>(new KeyFactory(), new ProxyClassFactory()); 11...
如下List-8是ProxyClassFactory类的定义,会调用apply方法,这个方法里面
- 1处需要重新加载下接口,为什么:这是因为已经加载了这些接口类不一定是传入的ClassLoader来加载的,Class.forname可以加载类,也可以控制是否初始化,这里参数是false所以不会初始化,ClassLoader.loadClass也可以加载类,但是它俩是有区别的。
- 2处生成动态代理类的完全路径名称
- 3处生成字节数组,ProxyGenerator.generateProxyClass__是sun包下面的
- 4处将字节数组生成类
List-8
1private static final class ProxyClassFactory 2 implements BiFunction<ClassLoader, Class<?>[], Class<?>> 3{ 4 // prefix for all proxy class names 5 private static final String proxyClassNamePrefix = "$Proxy"; 6 7 // next number to use for generation of unique proxy class names 8 private static final AtomicLong nextUniqueNumber = new AtomicLong(); 9 10 @Override 11 public Class<?> apply(ClassLoader loader, Class<?>[] interfaces) { 12 13 Map<Class<?>, Boolean> interfaceSet = new IdentityHashMap<>(interfaces.length); 14 for (Class<?> intf : interfaces) { 15 /* 16 * Verify that the class loader resolves the name of this 17 * interface to the same Class object. 18 */ 19 Class<?> interfaceClass = null; 20 try { 21 interfaceClass = Class.forName(intf.getName(), false, loader);//1 22 } catch (ClassNotFoundException e) { 23 } 24 if (interfaceClass != intf) { 25 throw new IllegalArgumentException( 26 intf + " is not visible from class loader"); 27 } 28 /* 29 * Verify that the Class object actually represents an 30 * interface. 31 */ 32 if (!interfaceClass.isInterface()) { 33 throw new IllegalArgumentException( 34 interfaceClass.getName() + " is not an interface"); 35 } 36 /* 37 * Verify that this interface is not a duplicate. 38 */ 39 if (interfaceSet.put(interfaceClass, Boolean.TRUE) != null) { 40 throw new IllegalArgumentException( 41 "repeated interface: " + interfaceClass.getName()); 42 } 43 } 44 45 String proxyPkg = null; // package to define proxy class in 46 int accessFlags = Modifier.PUBLIC | Modifier.FINAL; 47 48 /* 49 * Record the package of a non-public proxy interface so that the 50 * proxy class will be defined in the same package. Verify that 51 * all non-public proxy interfaces are in the same package. 52 */ 53 for (Class<?> intf : interfaces) { 54 int flags = intf.getModifiers(); 55 if (!Modifier.isPublic(flags)) { 56 accessFlags = Modifier.FINAL; 57 String name = intf.getName(); 58 int n = name.lastIndexOf('.'); 59 String pkg = ((n == -1) ? "" : name.substring(0, n + 1)); 60 if (proxyPkg == null) { 61 proxyPkg = pkg; 62 } else if (!pkg.equals(proxyPkg)) { 63 throw new IllegalArgumentException( 64 "non-public interfaces from different packages"); 65 } 66 } 67 } 68 69 if (proxyPkg == null) { 70 // if no non-public proxy interfaces, use com.sun.proxy package 71 proxyPkg = ReflectUtil.PROXY_PACKAGE + "."; 72 } 73 74 /* 75 * Choose a name for the proxy class to generate. 76 */ 77 long num = nextUniqueNumber.getAndIncrement(); 78 String proxyName = proxyPkg + proxyClassNamePrefix + num;//2 79 80 /* 81 * Generate the specified proxy class. 82 */ 83 byte[] proxyClassFile = ProxyGenerator.generateProxyClass( 84 proxyName, interfaces, accessFlags);//3 85 try { 86 return defineClass0(loader, proxyName, 87 proxyClassFile, 0, proxyClassFile.length);//4 88 } catch (ClassFormatError e) { 89 /* 90 * A ClassFormatError here means that (barring bugs in the 91 * proxy class generation code) there was some other 92 * invalid aspect of the arguments supplied to the proxy 93 * class creation (such as virtual machine limitations 94 * exceeded). 95 */ 96 throw new IllegalArgumentException(e.toString()); 97 } 98 } 99}
字节码生成的$Proxy类里面,接口实现上直接调用了invocationHandler.invoke方法,见https://mp.weixin.qq.com/s/gDO6t89gqgcAglA2jkdwVQ