Proxy.newProxyInstance源碼探究

 JDK動態代理案例實現:實現 InvocationHandler 接口重寫 invoke 方法,其中包含一個對象變量和提供一個包含對象的構造方法;

public class MyInvocationHandler implements InvocationHandler {
    Object target;//目標對象
    public MyInvocationHandler(Object target){
        this.target=target;
    }
    /**
     * @param proxy 代理對象
     * @param method 目標對象的目標方法
     * @param args    目標方法的參數
     */
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println("log");
        return method.invoke(target,args);
    }
}
public class MyInvocationHandlerTest {
    public static void main(String[] args) {
        //參數: 當前類的classLoader(保證MyInvocationHandlerTest當前類可用)
        //         接口數組:通過接口反射得到接口裏面的方法,對接口裏面的所有方法都進行代理
        //         實現的InvocationHandler:參數是目標對象
        UserDao jdkproxy = (UserDao) Proxy.newProxyInstance(MyInvocationHandlerTest.class.getClassLoader(),
                new Class[]{UserDao.class},new MyInvocationHandler(new UserService()));
        jdkproxy.query("query");
        //-----結果------
        //log
        //query
    }
}

  接下來查看 Proxy.newProxyInstance 源碼探究它的實現過程:  

    public static Object newProxyInstance(ClassLoader loader,
                                          Class<?>[] interfaces,
                                          InvocationHandler h)
        throws IllegalArgumentException
    {    
        //檢查InvocationHandler是否爲空,爲空拋出空指針異常
        Objects.requireNonNull(h);
        //克隆拿到接口
        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.doPrivileged(new PrivilegedAction<Void>() {
                    public Void run() {
                        cons.setAccessible(true);
                        return null;
                    }
                });
            }
            //new得到代理對象
            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);
        }
    }

  從上面可以看出 Class<?> cl = getProxyClass0(loader, intfs); 這行代碼最重要,它可以得到一個代理對象,下面是 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
    //如果接口的代理類已經存在緩存中了,直接從緩存中取出來返回,如果不存在則通過ProxyClassFactory創建一個並放入緩存中供下次使用 
        return proxyClassCache.get(loader, interfaces);
    }

  proxyClassCache.get() 的實現在 WeakCache#get() 中:

    public V get(K key, P parameter) {
        Objects.requireNonNull(parameter);

        expungeStaleEntries();
        //從緩存中取出代理類的key值,因爲代理類的生成需要耗時間和性能,所有緩存起來方便下次直接使用
        Object cacheKey = 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) {
            ConcurrentMap<Object, Supplier<V>> oldValuesMap
                = map.putIfAbsent(cacheKey,
                                  valuesMap = new ConcurrentHashMap<>());
            if (oldValuesMap != null) {
                valuesMap = oldValuesMap;
            }
        }

        // create subKey and retrieve the possible Supplier<V> stored by that
        // subKey from valuesMap 獲取到接口信息
        Object subKey = Objects.requireNonNull(subKeyFactory.apply(key, parameter));
        Supplier<V> supplier = valuesMap.get(subKey);
        Factory factory = null;
        //開始進來supplier是null,所以執行後面的代碼創建一個Factory然後賦值給supplier
        while (true) {
            if (supplier != null) {
                // supplier might be a Factory or a CacheValue<V> instance
                //獲取到代理類
                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
            if (factory == null) {
                factory = new Factory(key, parameter, subKey, valuesMap);//通過接口信息和classLoader創建一個工廠
            }

            if (supplier == null) {
                supplier = valuesMap.putIfAbsent(subKey, factory);
                if (supplier == null) {
                    // successfully installed Factory
                    supplier = factory;
                }
                // else retry with winning supplier
            } else {
                if (valuesMap.replace(subKey, supplier, factory)) {
                    // successfully replaced
                    // cleared CacheEntry / unsuccessful Factory
                    // with our Factory
                    supplier = factory;//將工廠賦值給supplier
                } else {
                    // retry with current supplier
                    supplier = valuesMap.get(subKey);
                }
            }
        }
    }

  下面查看 supplier.get():WeakCache.Factory#get()

        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
                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;

            // wrap value with CacheValue (WeakReference)
            CacheValue<V> cacheValue = new CacheValue<>(value);//根據代理類創建一個緩存對象

            // put into reverseMap
            reverseMap.put(cacheValue, Boolean.TRUE);//將代理放入緩存中

            // try replacing us with CacheValue (this should always succeed)
            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;
        }

  接下來查看 Objects.requireNonNull() 中的 apply方法:Proxy.ProxyClassFactory#apply()

        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 {
                    //對接口再次裝載,相當classLoader.loadClass
                    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();
                //判斷接口的類型是否是public,如果不是public,將代理類放到目標對象同一目錄下
                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
                //默認定義包名
                //public static final String PROXY_PACKAGE = "com.sun.proxy";
                proxyPkg = ReflectUtil.PROXY_PACKAGE + ".";
            }

            /*
             * Choose a name for the proxy class to generate.
             */
            long num = nextUniqueNumber.getAndIncrement();
            //標識:private static final String proxyClassNamePrefix = "$Proxy";
            //隨機數(防止多線程測試相同的類名):long num = nextUniqueNumber.getAndIncrement();
            //代理類的名字:代理包名+ 標識+ 隨機數
            String proxyName = proxyPkg + proxyClassNamePrefix + num;

            /*
             * Generate the specified proxy class.
             * 產生指定的代理類信息,是二進制信息,可以使用IO流輸出代理類的Java文件(可查看前文有介紹)
             * ProxyGenerator.generateProxyClass()是一個靜態方法,所以可以外部直接調用
             */
            byte[] proxyClassFile = ProxyGenerator.generateProxyClass(
                proxyName, interfaces, accessFlags);
            try {
                //產生代理類,返回一個class:將byte字節碼轉換成class
                //defineClass0是一個native方法,由JVM實現的:private static native Class<?> defineClass0();
                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());
            }
        }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章