final Class<?>[] intfs = interfaces.clone(); // Android-changed: sm is always null // 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 { // Android-changed: sm is always null // if (sm != null) { // checkNewProxyPermission(Reflection.getCallerClass(), cl); // }
final Constructor<?> cons = cl.getConstructor(constructorParams); final InvocationHandler ih = h; if (!Modifier.isPublic(cl.getModifiers())) { // Android-changed: Removed AccessController.doPrivileged cons.setAccessible(true); } 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); } }
while (true) { // 如果二级缓存的值 supplier 不为 null if (supplier != null) { // 调用 get() 方法 // 关键4:Factory implements Supplier,则此处实际调用的是 Factory#get() V value = supplier.get(); // value 不为空 if (value != null) { // 返回 value 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)
// 如果 factory 等于 null if (factory == null) { // 实例化一个 Factory(作为二级缓存的值),作为 subKey (二级缓存的 key)对应的 value factory = new Factory(key, parameter, subKey, valuesMap); }
public synchronized V get() { // serialize access // 根据二级缓存的 key 获取 supplier Supplier<V> supplier = valuesMap.get(subKey); // 如果获取的 supplier 不是 Factory 类型 if (supplier != this) { return null; } // else still us (supplier == this)
// create new value V value = null; try { // valueFactory 通过 WeakCache 构造函数传入,实际为 ProxyClassFactory // 关键5:valueFactory.apply()->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) CacheValue<V> cacheValue = new CacheValue<>(value);
// try replacing us with CacheValue (this should always succeed) if (valuesMap.replace(subKey, this, cacheValue)) { // put also in reverseMap reverseMap.put(cacheValue, Boolean.TRUE); } else { throw new AssertionError("Should not reach here"); }
// successfully replaced us with new CacheValue -> return the value // wrapped by it return value; }
// 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();
@Override public Class<?> apply(ClassLoader loader, Class<?>[] interfaces) {
// 根据接口数组长度生成对应的 Map 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. * * 验证类加载器将此 interface 的名字解析成同一类对象 */ Class<?> interfaceClass = null; try { // 根据接口名获取接口对应的类对象 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. * * 验证此接口不是重复的 */ // 往接口数组对应的 map 中存入类对象,返回值不为 null 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)) { // 设置为 final accessFlags = Modifier.FINAL; String name = intf.getName(); int n = name.lastIndexOf('.'); String pkg = ((n == -1) ? "" : name.substring(0, n + 1)); // 包名为 null if (proxyPkg == null) { // 包名等于当前接口的包名 proxyPkg = pkg; } else if (!pkg.equals(proxyPkg)) {// 如果包名不相等 // 抛异常,非 public 的接口集合来自不同的包 throw new IllegalArgumentException( "non-public interfaces from different packages"); } } }
// 包名为 null if (proxyPkg == null) { // if no non-public proxy interfaces, use com.sun.proxy package // 如果 no non-public(即是 public)的代理接口集合,则使用包名 com.sun.proxy 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. * * 关键6:生成指定的代理类 */ 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()); } }
/** * {@code InvocationHandler} is the interface implemented by * the <i>invocation handler</i> of a proxy instance. * * <p>Each proxy instance has an associated invocation handler. * When a method is invoked on a proxy instance, the method * invocation is encoded and dispatched to the {@code invoke} * method of its invocation handler. * * @author Peter Jones * @see Proxy * @since 1.3 */
/** * Processes a method invocation on a proxy instance and returns * the result. This method will be invoked on an invocation handler * when a method is invoked on a proxy instance that it is * associated with. * * @param proxy the proxy instance that the method was invoked on * * @param method the {@code Method} instance corresponding to * the interface method invoked on the proxy instance. The declaring * class of the {@code Method} object will be the interface that * the method was declared in, which may be a superinterface of the * proxy interface that the proxy class inherits the method through. * * @param args an array of objects containing the values of the * arguments passed in the method invocation on the proxy instance, * or {@code null} if interface method takes no arguments. * Arguments of primitive types are wrapped in instances of the * appropriate primitive wrapper class, such as * {@code java.lang.Integer} or {@code java.lang.Boolean}. * * @return the value to return from the method invocation on the * proxy instance. If the declared return type of the interface * method is a primitive type, then the value returned by * this method must be an instance of the corresponding primitive * wrapper class; otherwise, it must be a type assignable to the * declared return type. If the value returned by this method is * {@code null} and the interface method's return type is * primitive, then a {@code NullPointerException} will be * thrown by the method invocation on the proxy instance. If the * value returned by this method is otherwise not compatible with * the interface method's declared return type as described above, * a {@code ClassCastException} will be thrown by the method * invocation on the proxy instance. * * @throws Throwable the exception to throw from the method * invocation on the proxy instance. The exception's type must be * assignable either to any of the exception types declared in the * {@code throws} clause of the interface method or to the * unchecked exception types {@code java.lang.RuntimeException} * or {@code java.lang.Error}. If a checked exception is * thrown by this method that is not assignable to any of the * exception types declared in the {@code throws} clause of * the interface method, then an * {@link UndeclaredThrowableException} containing the * exception that was thrown by this method will be thrown by the * method invocation on the proxy instance. * * @see UndeclaredThrowableException */ public Object invoke(Object proxy, Method method, Object[] args) throws Throwable;