//此方法也是Proxy类下的方法 privatestatic Class getProxyClass0(ClassLoader loader, Class... interfaces) { if (interfaces.length > 65535) { thrownew 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 //意思是:如果代理类被指定的类加载器loader定义了,并实现了给定的接口interfaces, //那么就返回缓存的代理类对象,否则使用ProxyClassFactory创建代理类。 return proxyClassCache.get(loader, interfaces); }
这里看到proxyClassCache,有Cache便知道是缓存的意思,正好呼应了前面Look up or generate the designated proxy class。查询(在缓存中已经有)或生成指定的代理类的class对象这段注释。
/** * a cache of proxy classes */ privatestatic final WeakCache[], Class> proxyClassCache = new WeakCache<>(new KeyFactory(), new ProxyClassFactory());
privatefinal ReferenceQueuerefQueue = new ReferenceQueue<>(); // the key type is Object for supporting null key privatefinal ConcurrentMap subKeyFactory; privatefinal BiFunctionvalueFactory;
//K和P就是WeakCache定义中的泛型,key是类加载器,parameter是接口类数组 public V get(K key, P parameter) { //检查parameter不为空 Objects.requireNonNull(parameter); //清除无效的缓存 expungeStaleEntries(); // cacheKey就是(key, sub-key) -> value里的一级key, Object cacheKey = CacheKey.valueOf(key, refQueue);
// lazily install the 2nd level valuesMap for the particular cacheKey //根据一级key得到 ConcurrentMap ConcurrentMap> valuesMap = map.get(cacheKey); if (valuesMap == null) { ConcurrentMap> oldValuesMap = map.putIfAbsent(cacheKey, valuesMap = new ConcurrentHashMap<>()); if (oldValuesMap != null) { valuesMap = oldValuesMap; } }
// create subKey and retrieve the possible Supplierstored by that // subKey from valuesMap //这部分就是调用生成sub-key的代码,上面我们已经看过怎么生成的了 Object subKey = Objects.requireNonNull(subKeyFactory.apply(key, parameter)); //通过sub-key得到supplier Suppliersupplier = valuesMap.get(subKey); //supplier实际上就是这个factory Factory factory = null;
while (true) { //如果缓存里有supplier ,那就直接通过get方法,得到代理类对象,返回,就结束了,一会儿分析get方法。 if (supplier != null) { // supplier might be a Factory or a CacheValueinstance V value = supplier.get(); if (value != null) { returnvalue; } } // 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 //下面的所有代码目的就是:如果缓存中没有supplier,则创建一个Factory对象,把factory对象在多线程的环境下安全的赋给supplier。 //因为是在while(true)中,赋值成功后又回到上面去调get方法,返回才结束。 if (factory == null) { factory = new Factory(key, parameter, subKey, valuesMap); }
if (supplier == null) { supplier = valuesMap.putIfAbsent(subKey, factory); if (supplier == null) { // successfully installed Factory supplier = factory; } // else retry with winning supplier } else { if (valuesMap.replace(subKey, supplier, factory)) { // successfully replaced // cleared CacheEntry / unsuccessful Factory // with our Factory supplier = factory; } else { // retry with current supplier supplier = valuesMap.get(subKey); } } } }
所以接下来我们看Factory类中的get方法。
public synchronized V get() { // serialize access // re-check Suppliersupplier = valuesMap.get(subKey); /重新检查得到的supplier是不是当前对象 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 V value = null; try { //代理类就是在这个位置调用valueFactory生成的 //valueFactory就是我们传入的 new ProxyClassFactory() //一会我们分析ProxyClassFactory()的apply方法 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) //把value包装成弱引用 CacheValuecacheValue = new CacheValue<>(value);
// put into reverseMap // reverseMap是用来实现缓存的有效性 reverseMap.put(cacheValue, Boolean.TRUE);
// try replacing us with CacheValue (this should always succeed) if (!valuesMap.replace(subKey, this, cacheValue)) { thrownew AssertionError("Should not reach here"); }
// successfully replaced us with new CacheValue -> return the value // wrapped by it returnvalue; } }
拨云见日,来到ProxyClassFactory的apply方法,代理类就是在这里生成的。
//这里的BiFunction是个函数式接口,可以理解为用T,U两种类型做参数,得到R类型的返回值 privatestatic final class ProxyClassFactory implements BiFunction[], Class> { // prefix for all proxy class names //所有代理类名字的前缀 privatestatic final String proxyClassNamePrefix = "$Proxy";
// next number to use for generation of unique proxy class names //用于生成代理类名字的计数器 privatestatic final AtomicLong nextUniqueNumber = new AtomicLong();
@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 { interfaceClass = Class.forName(intf.getName(), false, loader); } catch (ClassNotFoundException e) { } if (interfaceClass != intf) { thrownew IllegalArgumentException( intf + " is not visible from class loader"); } /* * Verify that the Class object actually represents an * interface. */ if (!interfaceClass.isInterface()) { thrownew IllegalArgumentException( interfaceClass.getName() + " is not an interface"); } /* * Verify that this interface is not a duplicate. */ if (interfaceSet.put(interfaceClass, Boolean.TRUE) != null) { thrownew 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. */ //验证所有非公共的接口在同一个包内;公共的就无需处理 //生成包名和类名的逻辑,包名默认是com.sun.proxy,类名默认是$Proxy 加上一个自增的整数值 //如果被代理类是 non-public proxy 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; } elseif (!pkg.equals(proxyPkg)) { thrownew IllegalArgumentException( "non-public interfaces from different packages"); } } }
if (proxyPkg == null) { // if no non-public proxy interfaces, use com.sun.proxy package proxyPkg = ReflectUtil.PROXY_PACKAGE + "."; }
/* * Choose a name for the proxy class to generate. */ long num = nextUniqueNumber.getAndIncrement(); //代理类的完全限定名,如com.sun.proxy.$Proxy0.calss String proxyName = proxyPkg + proxyClassNamePrefix + num;
/* * Generate the specified proxy class. */ //核心部分,生成代理类的字节码 byte[] proxyClassFile = ProxyGenerator.generateProxyClass( proxyName, interfaces, accessFlags); try { //把代理类加载到JVM中,至此动态代理过程基本结束了 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). */ thrownew IllegalArgumentException(e.toString()); } } }
还没有评论,来说两句吧...