【趣味設計模式系列】之【代理模式2--JDK動態代理原始碼解析】

小豬爸爸發表於2020-08-13

1. 圖解

上圖主要描述了JDK動態代理的執行過程,下面做詳細分析。

2. Proxy原始碼分析

上一篇,在使用JDK動態代理的時候,藉助於Proxy類,使用newProxyInstance靜態方法,建立了動態代理物件,這個方法接收三個引數,分別是目標類的類載入器、目標類實現的介面陣列、自定義的InvocationHandler類,下面從該方法開始,詳細分析該類如何生成的。本文所用JDK版本為1.8.0_161,為了保留原始碼英文註釋的原汁原味,未對英文註釋做刪減,並在程式碼後面加註中文註釋。

    public static Object newProxyInstance(ClassLoader loader,
                                          Class<?>[] interfaces,
                                          InvocationHandler h)
        throws IllegalArgumentException
    {
        Objects.requireNonNull(h);// 驗證InvocationHandler不為空

        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); //獲取引數型別是InvocationHandler.class的代理類構造器
            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}); //傳入InvocationHandler例項去構造一個代理類的例項
        } 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);
        }
    }

從上面程式碼可以看出,建立代理物件總共如下幾步:

  1. 對引數進行一些許可權校驗;
  2. getProxyClass0方法生成了代理類的類物件;
  3. 獲取引數型別是InvocationHandler.class的代理類構造器;
  4. 通過InvocationHandler例項的引用,去構造出一個代理類物件。

因為生成的代理類繼承自Proxy類,子類建立例項物件時,會優先呼叫父類Proxy的構造,所以最後會呼叫Proxy的構造器將InvocationHandler將引用傳入。
下面重點看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
        return proxyClassCache.get(loader, interfaces); // 如果實現給定介面的給定載入器所定義的代理類存在,則從快取取,否則通過ProxyClassFactory建立
    }

上述程式碼主要做了兩件事:

  1. 判斷代理類實現的介面不能大於65535這個數;
  2. 快取存在代理類,則從快取取,否則從ProxyClassFactory建立。

3. WeakCache原始碼

下面將繼續深入WeakCache的原始碼,分析proxyClassCache.get方法相關實現。

final class WeakCache<K, P, V> {

    private final ReferenceQueue<K> refQueue
        = new ReferenceQueue<>(); // Reference引用佇列
    // the key type is Object for supporting null key
    private final ConcurrentMap<Object, ConcurrentMap<Object, Supplier<V>>> map  //快取的底層實現, key為一級快取, value為二級快取。 為了支援null, map的key型別設定為Object
        = new ConcurrentHashMap<>();
    private final ConcurrentMap<Supplier<V>, Boolean> reverseMap  // 記錄了所有代理類生成器是否可用, 這是為了實現快取的過期機制
        = new ConcurrentHashMap<>();
    private final BiFunction<K, P, ?> subKeyFactory; //生成二級快取key的工廠, 這裡傳入的是KeyFactory
    private final BiFunction<K, P, V> valueFactory; //生成二級快取value的工廠, 這裡傳入的是ProxyClassFactory

    /**
     * Construct an instance of {@code WeakCache}
     *
     * @param subKeyFactory a function mapping a pair of
     *                      {@code (key, parameter) -> sub-key}
     * @param valueFactory  a function mapping a pair of
     *                      {@code (key, parameter) -> value}
     * @throws NullPointerException if {@code subKeyFactory} or
     *                              {@code valueFactory} is null.
     */
    public WeakCache(BiFunction<K, P, ?> subKeyFactory,  //構造器, 傳入生成二級快取key的工廠和生成二級快取value的工廠
                     BiFunction<K, P, V> valueFactory) {
        this.subKeyFactory = Objects.requireNonNull(subKeyFactory);
        this.valueFactory = Objects.requireNonNull(valueFactory);
    }

    /**
     * Look-up the value through the cache. This always evaluates the
     * {@code subKeyFactory} function and optionally evaluates
     * {@code valueFactory} function if there is no entry in the cache for given
     * pair of (key, subKey) or the entry has already been cleared.
     *
     * @param key       possibly null key
     * @param parameter parameter used together with key to create sub-key and
     *                  value (should not be null)
     * @return the cached value (never null)
     * @throws NullPointerException if {@code parameter} passed in or
     *                              {@code sub-key} calculated by
     *                              {@code subKeyFactory} or {@code value}
     *                              calculated by {@code valueFactory} is null.
     */
    public V get(K key, P parameter) {
        Objects.requireNonNull(parameter); //這裡要求實現的介面不能為空

        expungeStaleEntries(); //清除過期的快取

        Object cacheKey = CacheKey.valueOf(key, refQueue); //將ClassLoader包裝成CacheKey, 作為一級快取的key

        // lazily install the 2nd level valuesMap for the particular cacheKey
        ConcurrentMap<Object, Supplier<V>> valuesMap = map.get(cacheKey); // 懶載入獲取二級快取
        if (valuesMap == null) { //如果根據ClassLoader沒有獲取到對應的值
            ConcurrentMap<Object, Supplier<V>> oldValuesMap  // 如果不存在則放入,否則返回原先的值
                = map.putIfAbsent(cacheKey,
                                  valuesMap = new ConcurrentHashMap<>());
            if (oldValuesMap != null) { //如果oldValuesMap有值, 說明放入失敗
                valuesMap = oldValuesMap;
            }
        }

        // create subKey and retrieve the possible Supplier<V> stored by that
        // subKey from valuesMap
        Object subKey = Objects.requireNonNull(subKeyFactory.apply(key, parameter)); //根據代理類實現的介面陣列來生成二級快取key, 分為key0, key1, key2, keyx
        Supplier<V> supplier = valuesMap.get(subKey); //這裡通過subKey獲取到二級快取的值
        Factory factory = null;

        while (true) {  //這個迴圈提供了輪詢機制, 如果條件為假就繼續重試直到條件為真為止
            if (supplier != null) {
                // supplier might be a Factory or a CacheValue<V> instance
                V value = supplier.get(); // 在這裡supplier可能是一個Factory也可能會是一個CacheValue
                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
            if (factory == null) { //快取中沒有supplier
                factory = new Factory(key, parameter, subKey, valuesMap); //新建一個Factory例項作為subKey對應的值
            }

            if (supplier == null) { // supplier返回null
                supplier = valuesMap.putIfAbsent(subKey, factory);  //到這裡表明subKey沒有對應的值, 就將factory作為subKey的值放入
                if (supplier == null) {
                    // successfully installed Factory
                    supplier = factory;   //到這裡表明成功將factory放入快取
                }
                // else retry with winning supplier
            } else { //Factory 沒有成功裝入快取
                if (valuesMap.replace(subKey, supplier, factory)) { //期間可能其他執行緒修改了值, 那麼就將原先的值替換
                    // successfully replaced
                    // cleared CacheEntry / unsuccessful Factory
                    // with our Factory
                    supplier = factory;  //成功將factory替換成新的值
                } else {
                    // retry with current supplier
                    supplier = valuesMap.get(subKey); //替換失敗, 繼續使用原先的值
                }
            }
        }
    }
    //後面省略

WeakCache的成員變數map,是通過ConcurrentMap來完成的,key為一級快取, value為二級快取,型別也是ConcurrentMapreverseMap是為了實現快取的過期機制;subKeyFactory是二級快取key的生成工廠,通過構造器傳入Proxy類的KeyFactoryvalueFactory是二級快取value的生成工廠,通過構造器傳入Proxy類的ProxyClassFactory

get方法大致做了如下幾步:

  1. ClassLoader包裝成CacheKey, 作為一級快取的key
  2. 懶載入獲取二級快取valuesMap
  3. 根據代理類實現的介面陣列來生成二級快取subKey
  4. 這裡通過二級快取的subKey獲取到二級快取的值;
  5. 若快取中沒有值、或者返回null、或者Factory例項沒有成功裝載,通過輪詢方式獲取二級快取的值,直到快取的值被裝載進去。

這裡的二級快取的值是一個Factory例項,最終代理類的值是通過Factory這個工廠來獲得的。

    /**
     * A factory {@link Supplier} that implements the lazy synchronized
     * construction of the value and installment of it into the cache.
     */
    private final class Factory implements Supplier<V> {

        private final K key;  //一級快取key, 根據ClassLoader生成
        private final P parameter; //代理類實現的介面陣列
        private final Object subKey; //二級快取key, 根據介面陣列生成
        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); //再次檢查並獲取二級快取裡面的Supplier, 用來驗證是否是Factory本身
            if (supplier != this) {  //在這裡驗證supplier是否是Factory例項本身, 如果不是則返回null讓呼叫者繼續輪詢重試;
                // 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
                return null;
            }
            // else still us (supplier == this)

            // create new value
            V value = null;
            try {
                value = Objects.requireNonNull(valueFactory.apply(key, parameter)); // 通過valueFactory生成代理類, 實際傳入ProxyClassFactory去生成代理類
            } 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; //只有value的值不為空才能到達這裡

            // wrap value with CacheValue (WeakReference)
            CacheValue<V> cacheValue = new CacheValue<>(value); //使用弱引用包裝生成的代理類

            // put into reverseMap
            reverseMap.put(cacheValue, Boolean.TRUE);  //將包裝後的cacheValue作為可用的代理類,放入reverseMap中

            // try replacing us with CacheValue (this should always succeed)
            if (!valuesMap.replace(subKey, this, cacheValue)) { //將包裝後的cacheValue放入二級快取中, 這個操作必須成功, 否則就報錯
                throw new AssertionError("Should not reach here");
            }

            // successfully replaced us with new CacheValue -> return the value
            // wrapped by it
            return value;  //最後返回未被弱引用包裝的原始代理類value
        }
    }

內部類Factoryget方法是使用synchronized關鍵字進行了同步,主要做了如下幾步:

  1. 檢查並獲取二級快取裡面的Supplier, 驗證是否是Factory本身;
  2. 如果1不是,則返回null,讓呼叫者繼續輪詢重試;
  3. 如果1是,則通過valueFactory生成代理類, 實際傳入ProxyClassFactory去生成代理類;
  4. 如果生成代理類失敗, 就將這個二級快取刪除;
  5. 斷言,只有代理類生成成功才能繼續下面步驟;
  6. 使用弱引用包裝生成的代理類;
  7. 將包裝後的cacheValue作為可用的代理類,放入reverseMap中;
  8. 將包裝後的cacheValue放入二級快取中, 且操作必須成功;
  9. 最後返回未被弱引用包裝的原始代理類value

至此,WeakCache一級快取和二級快取實現的原理,已經闡述清楚,上述過程中的第3步,二級快取key生成的原理,是怎樣通過Proxy的內部類ProxyClassFactory來生成代理類的,下面繼續深入ProxyGenerator這個類,分享代理類的位元組碼生成過程。

4. ProxyClassFactory原始碼分析

    /**
     * A factory function that generates, defines and returns the proxy class given
     * the ClassLoader and array of interfaces.
     */
    private static final class ProxyClassFactory
        implements BiFunction<ClassLoader, Class<?>[], Class<?>>
    {
        // prefix for all proxy class names
        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<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) { // intf是否可以由指定的類載入進行載入
                    throw new IllegalArgumentException(
                        intf + " is not visible from class loader");
                }
                /*
                 * Verify that the Class object actually represents an
                 * interface.
                 */
                if (!interfaceClass.isInterface()) { // intf是否是一個介面
                    throw new IllegalArgumentException(
                        interfaceClass.getName() + " is not an interface");
                }
                /*
                 * Verify that this interface is not a duplicate.
                 */
                if (interfaceSet.put(interfaceClass, Boolean.TRUE) != null) { // intf在陣列中是否有重複
                    throw new IllegalArgumentException(
                        "repeated interface: " + interfaceClass.getName());
                }
            }

            String proxyPkg = null;     // package to define proxy class in  //生成代理類的包名
            int accessFlags = Modifier.PUBLIC | Modifier.FINAL;  //生成代理類的訪問標誌, 預設是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, 那麼生成代理類的包名和介面包名相同
                    accessFlags = Modifier.FINAL; //生成的代理類的訪問標誌設定為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)) {  //代理類如果實現不同包的介面, 並且介面都不是public的, 那麼就會在這裡報錯
                        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 + ".";  //如果介面訪問標誌都是public的話, 那生成的代理類都放到預設的包下:com.sun.proxy
            }

            /*
             * Choose a name for the proxy class to generate.
             */
            long num = nextUniqueNumber.getAndIncrement(); //生成代理類的序號
            String proxyName = proxyPkg + proxyClassNamePrefix + num; //生成代理類的全限定名, 包名+字首+序號, 例如:com.sun.proxy.$Proxy0

            /*
             * Generate the specified proxy class.
             */
            byte[] proxyClassFile = ProxyGenerator.generateProxyClass(
                proxyName, interfaces, accessFlags);   // 用ProxyGenerator來生成位元組碼, 該類放在sun.misc包下
            try {
                return defineClass0(loader, proxyName,
                                    proxyClassFile, 0, proxyClassFile.length); //根據二進位制檔案生成相應的Class例項
            } 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());
            }
        }
    }

上述程式碼主要完成以下步驟:

  1. 判斷介面是否由指定類的載入器載入、是否是介面、介面是否重複;
  2. 指定生成包名類名的相關規則,介面訪問標誌都是public,代理類都放到預設的com.sun.proxy包下,介面的訪問標誌不是public, 那麼生成代理類的包名和介面包名相同;
  3. 通過ProxyGenerator類的generateProxyClass方法生成位元組碼檔案;
  4. 根據二進位制檔案生成相應的代理類例項。
    第3步是關鍵,下面將進一步分析ProxyGenerator類的generateProxyClass方法。

5. ProxyGenerator原始碼分析

由於ProxyGenerator類不在jdk中,需要下載openjdk才能看到原始碼,openjdk1.8官網下載地址如下http://hg.openjdk.java.net/jdk8/jdk8/jdk/archive/tip.zip,解壓後在openjdk\jdk\src\share\classes\sun\misc下面。

    /**
     * Generate a class file for the proxy class.  This method drives the
     * class file generation process.
     */
    private byte[] generateClassFile() {

        /* ============================================================
         * Step 1: Assemble ProxyMethod objects for all methods to
         * generate proxy dispatching code for.
         */
        //第一步, 將所有的方法組裝成ProxyMethod物件
        /*
         * Record that proxy methods are needed for the hashCode, equals,
         * and toString methods of java.lang.Object.  This is done before
         * the methods from the proxy interfaces so that the methods from
         * java.lang.Object take precedence over duplicate methods in the
         * proxy interfaces.
         */
        addProxyMethod(hashCodeMethod, Object.class); //為代理類生成hashCode代理方法
        addProxyMethod(equalsMethod, Object.class); //為代理類生成equals代理方法
        addProxyMethod(toStringMethod, Object.class); //為代理類生成toString代理方法

        /*
         * Now record all of the methods from the proxy interfaces, giving
         * earlier interfaces precedence over later ones with duplicate
         * methods.
         */
        for (Class<?> intf : interfaces) {  //遍歷每一個介面的每一個方法, 並且為其生成ProxyMethod物件
            for (Method m : intf.getMethods()) {
                addProxyMethod(m, intf);
            }
        }

        /*
         * For each set of proxy methods with the same signature,
         * verify that the methods' return types are compatible.
         */
        for (List<ProxyMethod> sigmethods : proxyMethods.values()) {   //對於具有相同簽名的代理方法, 檢驗方法的返回值是否相容
            checkReturnTypes(sigmethods);
        }

        /* ============================================================
         * Step 2: Assemble FieldInfo and MethodInfo structs for all of
         * fields and methods in the class we are generating.
         */ //第二步, 組裝要生成的class檔案的所有的欄位資訊和方法資訊
        try {
            methods.add(generateConstructor()); //新增構造器方法

            for (List<ProxyMethod> sigmethods : proxyMethods.values()) {  //遍歷快取中的代理方法
                for (ProxyMethod pm : sigmethods) {

                    // add static field for method's Method object
                    fields.add(new FieldInfo(pm.methodFieldName,  //新增代理類的靜態欄位
                        "Ljava/lang/reflect/Method;",
                         ACC_PRIVATE | ACC_STATIC));

                    // generate code for proxy method and add it
                    methods.add(pm.generateMethod()); //新增代理類的代理方法
                }
            }

            methods.add(generateStaticInitializer());  //新增代理類的靜態欄位初始化方法

        } catch (IOException e) {
            throw new InternalError("unexpected I/O Exception", e);
        }

        if (methods.size() > 65535) {   //驗證方法和欄位集合不能大於65535
            throw new IllegalArgumentException("method limit exceeded");
        }
        if (fields.size() > 65535) {
            throw new IllegalArgumentException("field limit exceeded");
        }

        /* ============================================================
         * Step 3: Write the final class file.
         */
        //第三步, 寫入最終的class檔案
        /*
         * Make sure that constant pool indexes are reserved for the
         * following items before starting to write the final class file.
         */
        cp.getClass(dotToSlash(className)); //驗證常量池中存在代理類的全限定名
        cp.getClass(superclassName); //驗證常量池中存在代理類父類的全限定名, 父類名為:"java/lang/reflect/Proxy"
        for (Class<?> intf: interfaces) {  //驗證常量池存在代理類介面的全限定名
            cp.getClass(dotToSlash(intf.getName()));
        }

        /*
         * Disallow new constant pool additions beyond this point, since
         * we are about to write the final constant pool table.
         */
        cp.setReadOnly(); //接下來要開始寫入檔案了,設定常量池只讀

        ByteArrayOutputStream bout = new ByteArrayOutputStream();
        DataOutputStream dout = new DataOutputStream(bout);

        try {
            /*
             * Write all the items of the "ClassFile" structure.
             * See JVMS section 4.1.
             */
                                        // u4 magic;
            dout.writeInt(0xCAFEBABE); //1.寫入魔數
                                        // u2 minor_version;
            dout.writeShort(CLASSFILE_MINOR_VERSION); //2.寫入次版本號
                                        // u2 major_version;
            dout.writeShort(CLASSFILE_MAJOR_VERSION); //3.寫入主版本號

            cp.write(dout);             // (write constant pool)  //4.寫入常量池

                                        // u2 access_flags;
            dout.writeShort(accessFlags); //5.寫入訪問修飾符
                                        // u2 this_class;
            dout.writeShort(cp.getClass(dotToSlash(className))); //6.寫入類索引
                                        // u2 super_class;
            dout.writeShort(cp.getClass(superclassName)); //7.寫入父類索引, 生成的代理類都繼承自Proxy

                                        // u2 interfaces_count;
            dout.writeShort(interfaces.length); //8.寫入介面計數值
                                        // u2 interfaces[interfaces_count];
            for (Class<?> intf : interfaces) {
                dout.writeShort(cp.getClass( //9.寫入介面集合
                    dotToSlash(intf.getName())));
            }

                                        // u2 fields_count;
            dout.writeShort(fields.size()); //10.寫入欄位計數值
                                        // field_info fields[fields_count];
            for (FieldInfo f : fields) {
                f.write(dout); //11.寫入欄位集合
            }

                                        // u2 methods_count;
            dout.writeShort(methods.size());//12.寫入方法計數值
                                        // method_info methods[methods_count];
            for (MethodInfo m : methods) {
                m.write(dout); //13.寫入方法集合
            }

                                         // u2 attributes_count;
            dout.writeShort(0); // (no ClassFile attributes for proxy classes) //14.寫入屬性計數值, 代理類class檔案沒有屬性所以為0

        } catch (IOException e) {
            throw new InternalError("unexpected I/O Exception", e);
        }

        return bout.toByteArray(); //轉換成二進位制陣列輸出
    }

上述程式碼主要完成以下步驟:

  1. 收集所有要生成的代理方法,將其包裝成ProxyMethod物件並註冊到Map集合中;
  2. 收集所有要為Class檔案生成的欄位資訊和方法資訊;
  3. 完成了上面的工作後,開始組裝Class檔案。
    其中第2步是核心,為代理類生成欄位和方法,完成以下步驟:
    1.為代理類生成一個帶參構造器,傳入InvocationHandler例項的引用並呼叫父類的帶參構造器;
    2.遍歷代理方法Map集合,為每個代理方法生成對應的Method型別靜態域,並將其新增到fields集合中;
    3.遍歷代理方法Map集合,為每個代理方法生成對應的MethodInfo物件,並將其新增到methods集合中;
    4.為代理類生成靜態初始化方法,該靜態初始化方法主要是將每個代理方法的引用賦值給對應的靜態欄位。
    最終引用上一篇的例子,生成的代理類如下:
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package com.sun.proxy;

import com.wzj.proxy.v9.Sellalbe;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.lang.reflect.UndeclaredThrowableException;

public final class $Proxy0 extends Proxy implements Sellalbe {
    private static Method m1;
    private static Method m3;
    private static Method m2;
    private static Method m0;

    public $Proxy0(InvocationHandler var1) throws  {
        super(var1);
    }

    public final boolean equals(Object var1) throws  {
        try {
            return (Boolean)super.h.invoke(this, m1, new Object[]{var1});
        } catch (RuntimeException | Error var3) {
            throw var3;
        } catch (Throwable var4) {
            throw new UndeclaredThrowableException(var4);
        }
    }

    public final void secKill() throws  {
        try {
            super.h.invoke(this, m3, (Object[])null);
        } catch (RuntimeException | Error var2) {
            throw var2;
        } catch (Throwable var3) {
            throw new UndeclaredThrowableException(var3);
        }
    }

    public final String toString() throws  {
        try {
            return (String)super.h.invoke(this, m2, (Object[])null);
        } catch (RuntimeException | Error var2) {
            throw var2;
        } catch (Throwable var3) {
            throw new UndeclaredThrowableException(var3);
        }
    }

    public final int hashCode() throws  {
        try {
            return (Integer)super.h.invoke(this, m0, (Object[])null);
        } catch (RuntimeException | Error var2) {
            throw var2;
        } catch (Throwable var3) {
            throw new UndeclaredThrowableException(var3);
        }
    }

    static {
        try {
            m1 = Class.forName("java.lang.Object").getMethod("equals", Class.forName("java.lang.Object"));
            m3 = Class.forName("com.wzj.proxy.v9.Sellalbe").getMethod("secKill");
            m2 = Class.forName("java.lang.Object").getMethod("toString");
            m0 = Class.forName("java.lang.Object").getMethod("hashCode");
        } catch (NoSuchMethodException var2) {
            throw new NoSuchMethodError(var2.getMessage());
        } catch (ClassNotFoundException var3) {
            throw new NoClassDefFoundError(var3.getMessage());
        }
    }
}

到此為止,JDK動態代理的生成原理基本上分析完了,筆者通過多次除錯原始碼,並結合英文註解,理解並翻譯其中的主要步驟,讀者可以根據本文的分析,自己除錯JDK原始碼,相信也會有不一樣的收穫,文章如有分析不恰當之處,歡迎交流,一起進步。

相關文章