/** * 生成一个代理对象 * Generate a proxy class. Must call the checkProxyAccess method * to perform permission checks before calling this. */ privatestatic Class<?> getProxyClass0(ClassLoader loader, Class<?>... interfaces) { //接口数量不能大于65535 否则报错 具体为什么 不太清楚 if (interfaces.length > 65535) { thrownewIllegalArgumentException("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); }
// lazily install the 2nd level valuesMap for the particular cacheKey // 从缓存map中读取指定cacheKey的缓存数据valuesMap ConcurrentMap<Object, Supplier<V>> valuesMap = map.get(cacheKey); if (valuesMap == null) { //如果valuesMap为null,则新增 // putIfAbsent方法解释:如果值存在则返回值,并且不对原来的值做任何更改,如果不存在则新增,并返回null //map.putIfAbsent 是map中新增的一个方法 存在则返回,不存在put然后在返回 ConcurrentMap<Object, Supplier<V>> oldValuesMap = map.putIfAbsent(cacheKey, valuesMap = newConcurrentHashMap<>()); //赋值 if (oldValuesMap != null) { valuesMap = oldValuesMap; } }
// create subKey and retrieve the possible Supplier<V> stored by that // subKey from valuesMap //获取subKey,这里用到了上面提到的Proxy的静态内部类 KeyFactory:subKeyFactory.apply(ket,parameter) ObjectsubKey= Objects.requireNonNull(subKeyFactory.apply(key, parameter)); // 从valuesMap中获取supplier Supplier<V> supplier = valuesMap.get(subKey); WeakCache.Factoryfactory=null;
while (true) { if (supplier != null) { // supplier might be a Factory or a CacheValue<V> instance // 4、从工厂中获取代理类对象 Vvalue= supplier.get(); if (value != null) { //5、返回 return value; } } // else no supplier in cache // or a supplier that returned null (could be a cleared CacheValue // or a Factory that wasn't successful in installing the CacheValue)
// lazily construct a Factory //1、实例化工厂 if (factory == null) { factory = newWeakCache.Factory(key, parameter, subKey, valuesMap); }
@Override publicsynchronized V get() { // serialize access // re-check //检查 如果 supplier不是自己 返回 Supplier<V> 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 returnnull; } // else still us (supplier == this)
// create new value //定义一个新的对象 Vvalue=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<V> cacheValue = newWeakCache.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)) { thrownewAssertionError("Should not reach here"); }
// successfully replaced us with new CacheValue -> return the value // wrapped by it //返回对象 return value; } }
我们核心注意的是
1
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. */ privatestaticfinalclassProxyClassFactory implementsBiFunction<ClassLoader, Class<?>[], Class<?>> { // prefix for all proxy class names //所有代理类对象的前缀 这个就回答了为什么代理类都带有$Proxy privatestaticfinalStringproxyClassNamePrefix="$Proxy";
// next number to use for generation of unique proxy class names //用于生成唯一代理类名称的下一个数字 privatestaticfinalAtomicLongnextUniqueNumber=newAtomicLong();
Map<Class<?>, Boolean> interfaceSet = newIdentityHashMap<>(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) { thrownewIllegalArgumentException( intf + " is not visible from class loader"); } /* * Verify that the Class object actually represents an * interface. * 验证是否是接口 不是接口报错 */ if (!interfaceClass.isInterface()) { thrownewIllegalArgumentException( interfaceClass.getName() + " is not an interface"); } /* * Verify that this interface is not a duplicate. * 验证此接口不是重复的,重复的就报错 */ if (interfaceSet.put(interfaceClass, Boolean.TRUE) != null) { thrownewIllegalArgumentException( "repeated interface: " + interfaceClass.getName()); } }
//代理类的包名 StringproxyPkg=null; // package to define proxy class in //访问权限 intaccessFlags= 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) { intflags= intf.getModifiers(); //如果接口是public就跳过 我们的接口基本上不会走这里 if (!Modifier.isPublic(flags)) { accessFlags = Modifier.FINAL; Stringname= intf.getName(); intn= name.lastIndexOf('.'); Stringpkg= ((n == -1) ? "" : name.substring(0, n + 1)); if (proxyPkg == null) { proxyPkg = pkg; } elseif (!pkg.equals(proxyPkg)) { thrownewIllegalArgumentException( "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. * 生成代理类的类名 */ //生成代理类的序号 longnum= nextUniqueNumber.getAndIncrement(); //生成代理类的完全限定名 StringproxyName= 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). */ thrownewIllegalArgumentException(e.toString()); } } }