KeyFactory实例对象的apply方法生产代理类缓存的Key
Factory实例对象的get()方法,获取或生产代理类并缓存到代理类缓存
ProxyClassFactory实例对象的apply方法生产代理类
核心类
Proxy : 生产代理对象的类
InvocationHandler : 实现代理逻辑的回调接口
InvocationHandler 接口作用详解
核心方法
public Object invoke(Object proxy,//代理对象 Method method, //要执行的方法对象 Object[] args //参数列表 ) throws Throwable;
在此方法中完成代理逻辑编写,以及目标方法调用;
@Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { System.out.println("前置代理逻辑"); Object invoke = method.invoke(target, args);//目标方法调用 System.out.println("后置代理逻辑"); return invoke; }
注意接口实现类中要维护目标对象,因为调用目标方法时要用到目标对象
public class MyInvocationHandler implements InvocationHandler { private Object target;//目标对象 public MyInvocationHandler(Object target){ this.target=target; } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { System.out.println("前置代理逻辑"); Object invoke = method.invoke(target, args);//目标方法调用 System.out.println("后置代理逻辑"); return invoke; } }
Proxy 类作用详解
产生代理类入口方法
源码分析
@CallerSensitive public static Object newProxyInstance(ClassLoader loader,//类加载器 Class<?>[] interfaces,//代理接口列表 InvocationHandler h/回调接口实现代理逻辑以及目标方法调用 ) throws IllegalArgumentException { Objects.requireNonNull(h);//非空验证 final Class<?>[] intfs = interfaces.clone();//接口列表Class对象副本 final SecurityManager sm = System.getSecurityManager();//Java安全管理器 if (sm != null) { checkProxyAccess(Reflection.getCallerClass(), loader, intfs);//安全以及权限校验 } /* * TODO 核心方法,获取代理类Class对象 */ Class<?> cl = getProxyClass0(loader, intfs); try { if (sm != null) { checkNewProxyPermission(Reflection.getCallerClass(), cl);//安全以及权限校验 } /* * 通过反射使用Class对象获取具有constructorParams参数类型的构造对象 * 参数 :constructorParams是什么? * private static final Class<?>[] constructorParams ={ InvocationHandler.class}; */ final Constructor<?> cons = cl.getConstructor(constructorParams); final InvocationHandler ih = h; if (!Modifier.isPublic(cl.getModifiers())) { AccessController.doPrivileged(new PrivilegedAction<Void>() { public Void run() { cons.setAccessible(true); return null; } }); } /*通过反射使用构造对象创建代理对象 *参数为InvocationHandler 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); } }
interfaces为接口列表的原因
因为对于目标对象,可能会实现多个接口,因此需要对多个接口同时代理
如果目标对象只实现了一个接口,传入一个接口即可
如果传入目标对象未实现的接口,在获取该接口代理对象在调用方法时会报错
loader 传入类加载器的原因
在获取代理类Class对象时使用, Class<?> cl = getProxyClass0(loader, intfs);
用于验证接口是否被同一类加载器加载
获取代理类Class对象
源码分析
Proxy静态方法获取代理类Class对象方法
private static Class<?> getProxyClass0(ClassLoader loader, Class<?>... interfaces) { //限制代理接口的个数 if (interfaces.length > 65535) { throw new IllegalArgumentException("interface limit exceeded"); } //如果指定类加载器实现定义的代理类 // 给定的接口存在, 这将简单的返回缓存副本 // 否则, 它将通过ProxyClassFactory创建代理类 return proxyClassCache.get(loader, interfaces); }
获取或者生产代理类并使用,WeakCache实例对象缓存
private final ReferenceQueue<K> refQueue = new ReferenceQueue<>(); //队列,生产类加载器缓存key时使用 private final ConcurrentMap<Object, ConcurrentMap<Object, Supplier<V>>> map = new ConcurrentHashMap<>();//各个类加载器缓存,ConcurrentMap<Object, Supplier<V>>为代理类缓存 private final ConcurrentMap<Supplier<V>, Boolean> reverseMap = new ConcurrentHashMap<>();//未知 private final BiFunction<K, P, ?> subKeyFactory;//代理类缓存Key工厂,实现类为Keyfactory private final BiFunction<K, P, V> valueFactory;//代理类Class工厂,实现类为ProxyClassFactory
public V get(K key, P parameter) { Objects.requireNonNull(parameter);//非空验证 expungeStaleEntries(); Object cacheKey = CacheKey.valueOf(key, refQueue);//根据类加载器和ReferenceQueue队列获取该类加载缓存代理类的key //根据cacheKey获取该类加载器的第2级缓存valuesMap,代理类的缓存,map是一级缓存,各个类加载的缓存 ConcurrentMap<Object, Supplier<V>> valuesMap = map.get(cacheKey); if (valuesMap == null) { //valuesMap为空时,给valuesMap创建新的ConcurrentHashMap并尝试放入 ConcurrentMap<Object, Supplier<V>> oldValuesMap = map.putIfAbsent(cacheKey, valuesMap = new ConcurrentHashMap<>()); if (oldValuesMap != null) { valuesMap = oldValuesMap;//如果valuesMap 已经存在则将已经存在的oldValuesMap对象赋给valuesMap } } // 根据parameter接口列表获取该类加载器的下代理类缓存valuesMap的subKey Object subKey = Objects.requireNonNull(subKeyFactory.apply(key, parameter)); //根据subKey获取三级缓存对象Supplier Supplier<V> supplier = valuesMap.get(subKey); Factory factory = null; //从supplier中获取代理类,supplier未初始化时进行初始化操作 while (true) { if (supplier != null) { V value = supplier.get();//核心方法:从Supplier获取代理或生产代理类 if (value != null) { return value; } } if (factory == null) { factory = new Factory(key, parameter, subKey, valuesMap); } //supplier 初始化操作 if (supplier == null) { supplier = valuesMap.putIfAbsent(subKey, factory); if (supplier == null) { supplier = factory; } } else { if (valuesMap.replace(subKey, supplier, factory)) { supplier = factory; } else { // retry with current supplier supplier = valuesMap.get(subKey); } } } }
KeyFactory实例对象的apply方法生产代理类缓存的Key
@Override public Object apply(ClassLoader classLoader, Class<?>[] interfaces) { switch (interfaces.length) { case 1: return new Key1(interfaces[0]); // the most frequent case 2: return new Key2(interfaces[0], interfaces[1]); case 0: return key0; default: return new KeyX(interfaces); } } }
Factory实例对象的get()方法,获取或生产代理类并缓存到代理类缓存
@Override public synchronized V get() { // serialize access // re-check Supplier<V> supplier = valuesMap.get(subKey); if (supplier != this) { return null; } // else still us (supplier == this) // create new value V value = null; try {//非空检验并使用valueFactory.apply(key, parameter)生产代理对象 value = Objects.requireNonNull(valueFactory.apply(key, parameter)); } finally { if (value == null) { // remove us on failure valuesMap.remove(subKey, this); } } assert value != null; // 创建缓存对象 CacheValue<V> cacheValue = new CacheValue<>(value); // 包装缓存对象 reverseMap.put(cacheValue, Boolean.TRUE); //放入缓存 if (!valuesMap.replace(subKey, this, cacheValue)) { throw new AssertionError("Should not reach here"); } return value; } }
ProxyClassFactory实例对象的apply方法生产代理类
@Override public Class<?> apply(ClassLoader loader, Class<?>[] interfaces) { Map<Class<?>, Boolean> interfaceSet = new IdentityHashMap<>(interfaces.length); for (Class<?> intf : interfaces) { /* * 验证类加载器是否解析了这个类的名称 * 指向同一个类对象的接口。 * */ 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"); } /* * 验证类对象是否实际表示接口 */ if (!interfaceClass.isInterface()) { throw new IllegalArgumentException( interfaceClass.getName() + " is not an interface"); } /* * 验证此接口不是重复的 */ if (interfaceSet.put(interfaceClass, Boolean.TRUE) != null) { throw new IllegalArgumentException( "repeated interface: " + interfaceClass.getName()); } } String proxyPkg = null; //代理类包名 int accessFlags = Modifier.PUBLIC | Modifier.FINAL; /* * 记录一个非公共代理接口包,以便代理类在同包中定义 * 验证所有非公共代理接口是否都在同一个包中 */ 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; } else if (!pkg.equals(proxyPkg)) { throw new IllegalArgumentException( "non-public interfaces from different packages"); } } } if (proxyPkg == null) { // 没有非公共代理接口时,使用默认的包,com.sun.proxy proxyPkg = ReflectUtil.PROXY_PACKAGE + "."; } /* * 给代理类名$Proxy后添加随机数方式并发 */ long num = nextUniqueNumber.getAndIncrement(); String proxyName = proxyPkg + proxyClassNamePrefix + num; /* * 生成代理类字节码 */ byte[] proxyClassFile = ProxyGenerator.generateProxyClass( proxyName, interfaces, accessFlags); try { //根据代理类字节码生成代理类类对象,native方法,使用C/C++完成 return defineClass0(loader, proxyName, proxyClassFile, 0, proxyClassFile.length); } catch (ClassFormatError e) { throw new IllegalArgumentException(e.toString()); } } }
gdk动态代理只支持基于接口代理的原因
因为jdk底层生成代理类时,继承了java.lang.reflect.Proxy类,
java只支持单继承,因此只能基于接口代理