Java 动态代理newProxyInstance

本文详细解析了Java动态代理机制的核心方法newProxyInstance的工作原理,包括如何生成代理类、类加载器验证、接口验证及代理类创建过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

newProxyInstance

该类的主题结构如下:(为了方便阅读,我删除了一些格式验证之类的代码)

    @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访问控制检查,这样就可以通过反射调用私有的参数和方法
  • 通过构造方法的构造函数传入调用处理程序创建目标对象的实例。各个参数自动解包以匹配原始形式参数,并且原始参数和参考参数都根据需要进行方法调用转换。

用一个简单的流程图表示这个方法的流程吧:

然后继续探究该方法会调用的几个主要方法:

getProxyClass0

该方法的方法注释就简单的一句话:

生成代理类。 在调用此方法之前,必须调用checkProxyAccess方法执行权限检查。

该方法主体如下:

    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方法开辟内存空间在内存中创建类。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值