六:代理模式

JDK 动态代理

JDK动态代理只能代理接口,内部通过实现接口完成代理。
源码分析 java.lang.reflect.Proxy#newProxyInstance

java.lang.reflect.Proxy#newProxyInstance
/**
*  loader  被代理类的加载器,用来加载代理类
* interfaces 被代理类继承的接口们
* h 需要增强处理的 Handler,代理类将 被代理类与h结合
**/
 @CallerSensitive
    public static Object newProxyInstance(ClassLoader loader,
                                          Class<?>[] interfaces,
                                          InvocationHandler h)
        throws IllegalArgumentException
    {
        Objects.requireNonNull(h);

        final Class<?>[] intfs = interfaces.clone();
       // 系统安全性校验
        final SecurityManager sm = System.getSecurityManager();
        if (sm != null) {
            checkProxyAccess(Reflection.getCallerClass(), loader, intfs);
        }

        /*
         * 1  寻找或者生成代理类.开始分析
         */
        Class<?> cl = getProxyClass0(loader, intfs);

        /*
         * Invoke its constructor with the designated invocation handler.
         */
        try {
            if (sm != null) {
                checkNewProxyPermission(Reflection.getCallerClass(), cl);
            }

            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;
                    }
                });
            }
            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);
        }
    }
java.lang.reflect.Proxy#getProxyClass0

  /**
     * 生成代理类
     */
    private static Class<?> getProxyClass0(ClassLoader loader,
                                           Class<?>... interfaces) {
        if (interfaces.length > 65535) {
            throw new 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

        // 2.从缓存中获取代理类,接下来分析 proxyClassCache
        // 代理类是什么时候放到缓存中的?如果生成的字节码文件?
       // 想知道以上问题需要先了解 WeakCache
        return proxyClassCache.get(loader, interfaces);
    }

  /**
     * a cache of proxy classes
     */
    private static final WeakCache<ClassLoader, Class<?>[], Class<?>>
        proxyClassCache = new WeakCache<>(new KeyFactory(), new ProxyClassFactory());
    // 上述代码调用了 proxyClassCache.get(loader, interfaces);
    即 java.lang.reflect.WeakCache#get方法

    /**
     * java.lang.reflect.WeakCache#get 方法
     * @param key
     * @param parameter
     * @return
     */
public V get(K key, P parameter) {
        Objects.requireNonNull(parameter);

        expungeStaleEntries();

        //第一级缓存的key
        Object cacheKey = java.lang.reflect.WeakCache.CacheKey.valueOf(key, refQueue);

        // lazily install the 2nd level valuesMap for the particular cacheKey
        // 懒加载第二级缓存
        ConcurrentMap<Object, Supplier<V>> valuesMap = map.get(cacheKey);
        if (valuesMap == null) {
            // 防止并发,如果map中已经存在cacheKey对应的valueMap 返回,如果没有 放进去空集合
            ConcurrentMap<Object, Supplier<V>> oldValuesMap
                    = map.putIfAbsent(cacheKey,
                    valuesMap = new ConcurrentHashMap<>());
            //如果cacheKey有对应的oldValuesMap,赋值给valueMap
            if (oldValuesMap != null) {
                valuesMap = oldValuesMap;
            }
        }

        // create subKey and retrieve the possible Supplier<V> stored by that
        // subKey from valuesMap
        // 根据subKeyFactory 获取subKey
        Object subKey = Objects.requireNonNull(subKeyFactory.apply(key, parameter));
        // valuesMap中获取subKey对应value
        Supplier<V> supplier = valuesMap.get(subKey);
        java.lang.reflect.WeakCache.Factory factory = null;

        while (true) {
            // 如果subKey 对应value supplier(WeakCache.Factory) 不为null 直接get,调用valueFactory.apply
            if (supplier != null) {
                // supplier might be a Factory or a CacheValue<V> instance
                // 第一次valueMap.subKey对应的value是Factory ,
                // 当调用一次valueFactory.apply之后,valuesMap.subKey value会替换为CacheValue
                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
            // 构建WeakCache.Factory 继承了Supplier
            if (factory == null) {
                factory = new java.lang.reflect.WeakCache.Factory(key, parameter, subKey, valuesMap);
            }

            if (supplier == null) {
                // 将subKey 对应factory 放入valuesMap中
                supplier = valuesMap.putIfAbsent(subKey, factory);
                //如果覆盖成功,supplier 返回一定为null,此时将factory赋值给supplier
                if (supplier == null) {
                    // successfully installed Factory
                    supplier = factory;
                }
                // else retry with winning supplier
            } else {
                // supplier不为空,走到这一步说明旧的supplier是无效的,所以用新生成的factory进行替换
                // 因为CacheValue是个弱引用,在动态代理中引用的是实际的代理类,如果该代理类不再使用被gc了
                if (valuesMap.replace(subKey, supplier, factory)) {
                    // successfully replaced
                    // cleared CacheEntry / unsuccessful Factory
                    // with our Factory
                    supplier = factory;
                } else {
                    // retry with current supplier
                    // 替换失败 则再次尝试用原来的supplier
                    supplier = valuesMap.get(subKey);
                }
            }
        }
    }

// 以上代码 看到了 subKey是keyFacotry.apply计算得到的,value呢?
是从哪里获取到的呢?这个需要看下supplier.get 即WeakCache.Factory.get

//com.mashibing.node.design.proxy.WeakCache.Factory
/**
* Factory即是Supplier,factroy.get最终调用valueFactory.apply方法
* 获取到value后通过CacheValue(也是Supplier)包装,
* 然后放到 valuesMap中
**/
 private final class Factory implements Supplier<V> {

        private final K key;
        private final P parameter;
        private final Object subKey;
        private final ConcurrentMap<Object, Supplier<V>> valuesMap;

        Factory(K key, P parameter, Object subKey,
                ConcurrentMap<Object, Supplier<V>> valuesMap) {
            this.key = key;
            this.parameter = parameter;
            this.subKey = subKey;
            this.valuesMap = valuesMap;
        }

        @Override
        public synchronized 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
                // 防止在调用过程supplier 被改变
                return null;
            }
            // else still us (supplier == this)

            // create new value
            V value = null;
            try {
            //获取实际的value值
                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;
            // 一定获取到了返回值 则通过cacheValue包装
            // wrap value with CacheValue (WeakReference)
            java.lang.reflect.WeakCache.CacheValue<V> cacheValue = new java.lang.reflect.WeakCache.CacheValue<>(value);

            // put into reverseMap
            reverseMap.put(cacheValue, Boolean.TRUE);

            // try replacing us with CacheValue (this should always succeed)
            // 将valueFactory.apply返回值,实际subKey的value的弱引用放入到valuesMap中
            // 注意CacheValue 继承了Value ,Value继承Supplier 所以在下一次
            // 在 weekCache.map get出来的valuesMap.get(subKey)中获取的就是 CacheValue
            // 所以 supplier might be a Factory or a CacheValue<V> instance
            if (!valuesMap.replace(subKey, this, cacheValue)) {
                throw new AssertionError("Should not reach here");
            }

            // successfully replaced us with new CacheValue -> return the value
            // wrapped by it
            return value;
        }
    }

WeekCache 看完了实现方式之后,回过头来继续看下中KeyFactory与ProxyClassFactory

  private static final WeakCache<ClassLoader, Class<?>[], Class<?>>
        proxyClassCache = new WeakCache<>(new KeyFactory(), new ProxyClassFactory());
/**
* KeyFactory 非常简单根据interface不同数量创建不同key不展开细说
* 但是可以确定Key extends WeakReference<Class<?>> 弱引用
**/
 private static final class KeyFactory
        implements BiFunction<ClassLoader, Class<?>[], Object>
    {
        @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);
            }
        }
    }

ProxyClassFactory 相对复杂些,我们分析get方法

@Override
        public Class<?> apply(ClassLoader loader, Class<?>[] 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) {
                    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.
                 */
                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();
                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) {
                // 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();
            String proxyName = proxyPkg + proxyClassNamePrefix + num;

            /*
             *  关注重点 生成字节码文件
             *  本部分内容不具体研究,其中 private static final boolean saveGeneratedFiles = (Boolean)AccessController.doPrivileged(new GetBooleanAction("sun.misc.ProxyGenerator.saveGeneratedFiles"));
               
              * System.getProperties().put("sun.misc.ProxyGenerator.saveGeneratedFiles", "true");
              * 将二进制流以文件的形式保存下来,就是在这里启用的
              * sun.misc.ProxyGenerator#generateProxyClass(java.lang.String, java.lang.Class<?>[], int)
             */
            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());
            }
        }
    }
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 一、基本概念 1.什么是代理? 在阐述JDK动态代理之前,我们很有必要先来弄明白代理的概念。代理这个词本身并不是计...
    小李弹花阅读 16,580评论 2 40
  • 追溯 学一个技术,要知道技术因何而产生,才能有学下去的目标和动力,才能更好的理解 首先,要明确为什么要存在代理呢?...
    洋仔聊编程阅读 427评论 0 6
  • 本文主要介绍JDK动态代理的基本原理,让大家更深刻的理解JDK Proxy,知其然知其所以然。明白JDK动态代理真...
    程序员日常填坑阅读 269评论 0 0
  • 定义 动态代理类的源码是在程序运行期间由JVM根据反射等机制动态的生成,所以不存在代理类的字节码文件。代理类和委托...
    赤子心_d709阅读 1,234评论 2 6
  • 我准备战斗到最后,不是因为我勇敢,是我想见证一切。 --双雪涛《猎人》 [TOC]Thinking 一个技术...
    小安的大情调阅读 346评论 0 2

友情链接更多精彩内容