Java--動態代理Proxy源碼分析

java的動態代理通過Proxy的newProxyInstance方法來創建代理對象

/*
        * 通過Proxy的newProxyInstance方法來創建代理對象
        * 第一個參數 handler.getClass().getClassLoader() ,使用handler這個類的ClassLoader對象來加載代理對象
        * 第二個參數realSubject.getClass().getInterfaces(),為代理對象提供的接口是真實對象所實行的接口,表示代理的是該真實對象,這樣就能調用這組接口中的方法了
        * 第三個參數handler,將這個代理對象關聯到了上方的 InvocationHandler 這個對象上
        */
        Hello helloProxy = (Hello)Proxy.newProxyInstance(handler.getClass().getClassLoader(), helloImpl
            .getClass().getInterfaces(), handler);

從newProxyInstance這個入口來看看Proxy的重點方法

public static Object newProxyInstance(ClassLoader loader,
                                          Class<?>[] interfaces,
                                          InvocationHandler h)
        throws IllegalArgumentException
    {
        //一個判空的方法
        Objects.requireNonNull(h);

        //將接口clone,之后對此clone類進行操作
        final Class<?>[] intfs = interfaces.clone();
        //進行權限檢查
        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 {
            if (sm != null) {
                checkNewProxyPermission(Reflection.getCallerClass(), cl);
            }

            //獲取構造
            final Constructor<?> cons = cl.getConstructor(constructorParams);
            final InvocationHandler ih = h;
            if (!Modifier.isPublic(cl.getModifiers())) {
                AccessController.doexposingd(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);
        }
    }

newProxyInstance幫我們執行了生成代理類----獲取構造器----生成代理對象這三步
再來看查找/生成的代理類getProxyClass0

private static Class<?> getProxyClass0(ClassLoader loader,
                                           Class<?>... interfaces) {
        //接口數量超過65535,報異常
        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
        //如果緩存中有,就直接返回
        return proxyClassCache.get(loader, interfaces);
    }
/**
     * a cache of proxy classes
     * 動態代理類的弱緩存容器
     * KeyFactory:根據接口的數量,映射一個最佳的key生成函數,其中表示接口的類對象被弱引用;
     * 也就是key對象被弱引用繼承自WeakReference(key0、key1、key2、keyX),
     * 保存接口密鑰(hash值)
     * ProxyClassFactory:生成動態類的工廠
     */
    private static final WeakCache<ClassLoader, Class<?>[], Class<?>>
        proxyClassCache = new WeakCache<>(new KeyFactory(), new ProxyClassFactory());
private static final class ProxyClassFactory
        implements BiFunction<ClassLoader, Class<?>[], Class<?>>
    {
        // prefix for all proxy class names
        //所有代理類的名稱,在demo中打出的結果“$Proxy0”中的“$Proxy”
        private static final String proxyClassNamePrefix = "$Proxy";

        // next number to use for generation of unique proxy class names
        //每一個代理都有一個數值,在demo中打出的結果“$Proxy0”中的“0”
        private static final AtomicLong nextUniqueNumber = new AtomicLong();

        @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;//設置一個flag,是public的或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)) {//如果接口不是public或final的
                    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
                //proxy類所在的包名
                proxyPkg = ReflectUtil.PROXY_PACKAGE + ".";
            }

            /*
             * Choose a name for the proxy class to generate.
             * 原子類,保證線程安全,防止類名重復
             */
            long num = nextUniqueNumber.getAndIncrement();
            //將包名與“$Proxy”,proxy類的唯一數值連接起來,就是demo中最終打出的“$Proxy0”
            String proxyName = proxyPkg + proxyClassNamePrefix + num;

            /*
             * Generate the specified proxy class.
             * 生成proxy類
             */
            byte[] proxyClassFile = ProxyGenerator.generateProxyClass(
                proxyName, interfaces, accessFlags);
            try {//調用一個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).
                 */
                throw new IllegalArgumentException(e.toString());
            }
        }
    }
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • Java代理和動態代理機制分析和應用 概述 代理是一種常用的設計模式,其目的就是為其他對象提供一個代理以控制對某個...
    丸_子閱讀 3,050評論 6 57
  • 從三月份找實習到現在,面了一些公司,掛了不少,但最終還是拿到小米、百度、阿里、京東、新浪、CVTE、樂視家的研發崗...
    時芥藍閱讀 42,366評論 11 349
  • 1、代理概念 為某個對象提供一個代理,以控制對這個對象的訪問。 代理類和委托類有共同的父類或父接口,這樣在任何使用...
    孔垂云閱讀 7,755評論 4 54
  • 今天周六,到了每隔一周我們的課程時間,我們今天要講的是藍色思維 在這過去的兩周,我們通過各種各樣的形式,來了解和學...
    Daisy7766閱讀 1,153評論 0 0
  • 有一個聽眾和我說,先生你說異地戀是不是就是如附骨之毒的思念。一個人孤獨的堅持,看得到卻摸不到,能說能聽,卻只有蒼白...
    輕逸先生閱讀 1,378評論 0 3