/** * Generate a proxy class. Must call the checkProxyAccess method * to perform permission checks before calling this. * 生成一个代理类。必须调用checkProxyAccess方法,在调用之前执行权限检查。 */ 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 //如果代理类由给定加载器定义实现 //给定的接口存在,这将返回缓存的副本; //否则,它将通过ProxyClassFactory创建代理类
// 利用 CAS + 重试机制 while (true) { if (supplier != null) { // supplier might be a Factory or a CacheValue<V> instance // 此supplier可能是缓存中取出来的,也可能是Factory新new出来的 V value = supplier.get(); if (value != null) { 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 // 懒加载建造工厂,初次循环一定为null,目的是上一步获取不到值工厂创建 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); } } } }
@Override // synchronized对获取代理类进行了同步限制 publicsynchronized V get(){ // serialize access // re-check 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 V value = null; try { // 生成代理类 value = Objects.requireNonNull(valueFactory.apply(key, parameter)); } finally { if (value == null) { // remove us on failure //移除值,便于GC,清理弱引用 valuesMap.remove(subKey, this); } } // the only path to reach here is with non-null value assert value != null;
// wrap value with CacheValue (WeakReference) // 用CacheValue (弱引用)包装值 CacheValue<V> cacheValue = new CacheValue<>(value);
// try replacing us with CacheValue (this should always succeed) // 更新factory为cacheValue if (valuesMap.replace(subKey, this, cacheValue)) { // put also in reverseMap reverseMap.put(cacheValue, Boolean.TRUE); } else { thrownew AssertionError("Should not reach here"); }
// successfully replaced us with new CacheValue -> return the value // wrapped by it return value; } }
/** * A factory function that generates, defines and returns the proxy class given * the ClassLoader and array of interfaces. */ privatestaticfinalclassProxyClassFactory implements BiFunction<ClassLoader, Class<?>[], Class<?>> { // prefix for all proxy class names privatestaticfinal String proxyClassNamePrefix = "$Proxy";
// next number to use for generation of unique proxy class names privatestaticfinal AtomicLong nextUniqueNumber = new AtomicLong();
@Override public Class<?> apply(ClassLoader loader, Class<?>[] interfaces) {
// loader:类加载器, interfaces:接口数组 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) { 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 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(); 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 // 如果没有非公共代理接口,则使用 com.sun.proxy 代理包 proxyPkg = ReflectUtil.PROXY_PACKAGE + "."; }
/* * Choose a name for the proxy class to generate. * 选择要生成的代理类的名称。 * private static final AtomicLong nextUniqueNumber = new AtomicLong(); * 原子类,确保多线程安全,防止类名重复,类似于:$Proxy0,$Proxy1...... */ long num = nextUniqueNumber.getAndIncrement(); String proxyName = proxyPkg + proxyClassNamePrefix + num; // $Proxy0,$Proxy1......
/* * Generate the specified proxy class. * 生成指定的代理类。 */
// 这是生成类字节码的方法:重点 byte[] proxyClassFile = ProxyGenerator.generateProxyClass( proxyName, interfaces, accessFlags); try { //字节码loader进内存,加载代理类对象。defineClass0是一个native方法 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()); } } }