Java 動態代理newProxyInstance

newProxyInstance

該類的主題結構以下:(爲了方便閱讀,我刪除了一些格式驗證之類的代碼)java

@CallerSensitive
    public static Object newProxyInstance(ClassLoader loader, Class<?>[] interfaces, InvocationHandler h) throws IllegalArgumentException {
        //克隆
        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;
                    }
                });
            }
            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);
        }
    }
複製代碼

逐行理解:緩存

  • 首先是方法註釋:

返回指定接口的代理類的實例,該接口將方法調用分派給指定的調用處理程序。安全

  • 由上可知該方法的主要功能是建立一個指定接口的代理類示例,而且將方法的調用分派給指定的調用處理程序:InvocationHandler,其餘參數分別是:類加載器、須要建立代理對象的接口的Class對象。
  • clone()接口的Class類並獲取系統的安全接口,安全接口主要用來檢查Class對象的權限(我是這樣理解的,有錯請指出)
  • 調用getProxyClass0方法生成代理類, Class<?> cl就是代理類的Class對象
  • 調用生成代理Class的getConstructor方法獲取其構造函數,並將調用處理程序的Class類做爲參數傳入
  • 檢查該代理Class的Java修飾符,便是否是public仍是protected
  • 若是該類不是public修飾,則將該對象強制設置爲運行時禁止java訪問控制檢查,這樣就能夠經過反射調用私有的參數和方法
  • 經過構造方法的構造函數傳入調用處理程序建立目標對象的實例。各個參數自動解包以匹配原始形式參數,而且原始參數和參考參數都根據須要進行方法調用轉換。

用一個簡單的流程圖表示這個方法的流程吧:app

而後繼續探究該方法會調用的幾個主要方法:ide

getProxyClass0

該方法的方法註釋就簡單的一句話:函數

生成代理類。 在調用此方法以前,必須調用checkProxyAccess方法執行權限檢查。this

該方法主體以下:spa

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建立代理類代理

同時這裏還會檢查目標接口的大小,若是超過65535則拋出異常,這是由JVM限制的,由於Java使用的是UNICODE標準字符集16位,最大爲65535.

接着看proxyClassCache參數

private static final WeakCache<ClassLoader, Class<?>[], Class<?>>
        proxyClassCache = new WeakCache<>(new KeyFactory(), new ProxyClassFactory());
複製代碼

這個類具體我也沒有使用過,經過查找類註釋得知該類的功能:

  1. 這是一個緩存映射對,映射關係:{(密鑰,子密鑰) -> 值}。
  2. 鍵和值是弱引用,會在GC的時候被清理,可是子鍵是強引用
  3. 使用構造函數所賦值的subKeyFactory函數從鍵和參數計算子鍵。
  4. 使用構造函數所賦值的valueFactory函數從鍵和參數計算值。

所以首次調用應該會調用new ProxyClassFactory()這個對象,的apply方法

ProxyClassFactory

這個類能夠看到它所實現的接口: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) {
                    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;

            /* * Generate the specified proxy class. */
            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());
            }
        }
複製代碼

看起來很長很複雜,其實大部分都是些參數驗證之類的功能,這裏我就按塊來過一遍:

類加載器驗證

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());
                }
            }
複製代碼

主要驗證

  1. 類加載器是否能夠加載目標接口的Class
  2. 類加載器加載的是不是接口類
  3. 檢查目標接口Class是否重複

包位置驗證

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 + ".";
            }
複製代碼

這段主要驗證的是:

  1. 接口是否在同一個包下的非public接口。若是是同一個包下的非pubic接口,則將目標修飾符從public final修改成final。並將包名賦值爲該接口所在的包名。若是是同一個包下的public接口,則使用默認的com.sun.proxy路徑

設置生成代理類的名稱

/* * Choose a name for the proxy class to generate. */
    long num = nextUniqueNumber.getAndIncrement();
    String proxyName = proxyPkg + proxyClassNamePrefix + num;
複製代碼

將前面的包名和默認的$Proxy前綴組合成該Class的名稱,這有點眼熟: com.sun.proxy$Proxy0,這有點相似於內存地址的toString()打印。

代理類生成

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());
    }
複製代碼

最後是調用ProxyGenerator.generateProxyClass方法並傳入代理類名稱,目標接口對象以及目標接口的修飾符來建立目標接口代理類的byte[],而後調用defineClass0方法開闢內存空間在內存中建立類。

相關文章
相關標籤/搜索