public static Object newProxyInstance(ClassLoader loader, Class>[] interfaces, InvocationHandler h) throws IllegalArgumentException { //增强实现不能为空,为空就抛出异常 Objects.requireNonNull(h); //对接口数组进行clone 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); } // 从代理类对象中查找参数为InvocationHandler的构造器 final Constructor> cons = cl.getConstructor(constructorParams); final InvocationHandler ih = h; // 检测构造器是否是Public修饰,如果不是则强行转换为可以访问的。 if (!Modifier.isPublic(cl.getModifiers())) { AccessController.doPrivileged(new PrivilegedAction() { public Void run() { cons.setAccessible(true); return null; } }); } //通过反射,将h作为参数,实例化代理类,返回代理类实例。 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); } }
上面代码的核心方法是
Class> cl = getProxyClass0(loader, intfs);
找到了核心方法继续深入
3、getProxyClass0方法入口
生成一个代理对象的方法
/** * 生成一个代理对象 * Generate a proxy class. Must call the checkProxyAccess method * to perform permission checks before calling this. */ private static Class> getProxyClass0(ClassLoader loader, Class>... interfaces) { //接口数量不能大于65535 否则报错 具体为什么 不太清楚 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; //否则,它将通过proxyClassFactory创建代理类 // otherwise, it will create the proxy class via the ProxyClassFactory return proxyClassCache.get(loader, interfaces); }
/** * a cache of proxy classes * 缓存代理的class字节码文件,如果没有则使用ProxyClassFactory创建 */ private static final WeakCache[], Class>> proxyClassCache = new WeakCache<>(new KeyFactory(), new ProxyClassFactory());
final class WeakCache { private final ReferenceQueue refQueue = new ReferenceQueue<>(); // the key type is Object for supporting null key // key的类型为Object,支持null key,这里的null key并不是真的可以使用null最为key,而是一个new Objdec()对象实例。ConcurrentHashMap,不允许键或值null,而HashMap可以。ConcurrentHashMap是线程安全的,HashMap不是。 private final ConcurrentMap
/** * Factory 实现类Supplier 接口 */ private final class Factory implements Supplier {//类加载器 loader private final K key; 接口的数组 interfaces private final P parameter; //这里的subkey 就是上面的 KeyFactory 可以会看 WeakCache 方法声明 private final Object subKey; //提供者的MAP key是KeyFactory ,value 是 Factory 本身 private final ConcurrentMap> valuesMap; //构造方法 Factory(K key, P parameter, Object subKey, ConcurrentMap> valuesMap) { this.key = key; this.parameter = parameter; this.subKey = subKey; this.valuesMap = valuesMap; } @Override public synchronized V get() { // serialize access // re-check //检查 如果 supplier不是自己 返回 Supplier supplier = valuesMap.get(subKey); if (supplier != this) { // something changed while we were waiting: // might be that we were replaced by a CacheValue // or were removed because of failure -> // return null to signal WeakCache.get() to retry // the loop return null; } // else still us (supplier == this) // create new value //定义一个新的对象 V value = null; try { /** * valueFactory就是WeakCache的valueFactory属性,因为Factory是WeakCache的内部类,所以可以直接访问WeakCache的valueFactory属性 * 我们可以回去看看第四第五 proxyClassCache.get 以及 WeakCache 的简单结构 注意valueFactory 发现就是 ProxyClassFactory * 就在这一步生成了 代理对象 */ value = Objects.requireNonNull(valueFactory.apply(key, parameter)); } finally { if (value == null) { // remove us on failure valuesMap.remove(subKey, this); } } // the only path to reach here is with non-null value //校验对象不为空 assert value != null; // wrap value with CacheValue (WeakReference) WeakCache.CacheValue cacheValue = new WeakCache.CacheValue<>(value); // put into reverseMap //缓存代理对象 reverseMap.put(cacheValue, Boolean.TRUE); // try replacing us with CacheValue (this should always succeed) //并将valuesMap替换为最新生成的对象 if (!valuesMap.replace(subKey, this, cacheValue)) { throw new AssertionError("Should not reach here"); } // successfully replaced us with new CacheValue -> return the value // wrapped by it //返回对象 return value; } }
我们核心注意的是
value = Objects.requireNonNull(valueFactory.apply(key, parameter));
/** * 一个利用给定的类加载器和接口类数组生成,定义并返回代理类对象的工厂方法 * A factory function that generates, defines and returns the proxy class given * the ClassLoader and array of interfaces. */ private static final class ProxyClassFactory implements BiFunction[], Class>> { // prefix for all proxy class names //所有代理类对象的前缀 这个就回答了为什么代理类都带有$Proxy private static final String proxyClassNamePrefix = "$Proxy"; // next number to use for generation of unique proxy class names //用于生成唯一代理类名称的下一个数字 private static final AtomicLong nextUniqueNumber = new AtomicLong(); /** * 开始我们的核心方法apply * @param loader 类加载器 * @param interfaces 接口数组 * @return */ @Override public Class> apply(ClassLoader loader, Class>[] interfaces) { Map, 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 { //加载接口类,获得接口类的类对象,第二个参数为false表示不进行实例化 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 Class object actually represents an * 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()); } } //代理类的包名 String proxyPkg = null; // package to define proxy class in //访问权限 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. */ for (Class> intf : interfaces) { int flags = intf.getModifiers(); //如果接口是public就跳过 我们的接口基本上不会走这里 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"); } } } if (proxyPkg == null) { // if no non-public proxy interfaces, use com.sun.proxy package //如果没有public的接口 就是用 com.sun.proxy 的包前缀 //类似于com.sun.proxy.$Proxy0 proxyPkg = ReflectUtil.PROXY_PACKAGE + "."; } /* * Choose a name for the proxy class to generate. * 生成代理类的类名 */ //生成代理类的序号 long num = nextUniqueNumber.getAndIncrement(); //生成代理类的完全限定名 String proxyName = proxyPkg + proxyClassNamePrefix + num; /* * Generate the specified proxy class. * 生成代理类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()); } } }