美文网首页Java 程序员
jdk动态代理原理解析

jdk动态代理原理解析

作者: Android程序员老鸦 | 来源:发表于2021-07-18 22:03 被阅读0次

    上篇文章研究了retrofit的源码,提到了一个重要的概念动态代理,这是一个很重要的知识点,打算详细梳理一下。
    相比于静态代理,动态代理的好处是可以让接口里的方法统一做一些处理,而不必要手动添加多个代理类。
    先来看一个使用例子,首先建一个接口类,带2个方法:

    public interface ServiceApi {
        void login();
        void loginOut();
    }
    

    来一个实现类:

    public class ServiceApiImp implements ServiceApi{
        @Override
        public void login() {
            Log.d("TAG","登录了");
        }
    
        @Override
        public void loginOut() {
            Log.d("TAG","退出登录了");
        }
    }
    

    再来一个InvocationHandler的子类:

    public class ServiceInvocationHandler implements InvocationHandler {
        private ServiceApi serviceApi;
        public ServiceInvocationHandler(ServiceApi serviceApi){
            this.serviceApi = serviceApi;
        }
        @Override
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            Log.d("TAG","执行了invoke");
            //执行传入的serviceApi的method,
            return method.invoke(serviceApi,args);
        }
    }
    

    使用:

    //新建ServiceApiImp对象
    ServiceApiImp serviceApiImp = new ServiceApiImp();
    //新建ServiceInvocationHandler 
    ServiceInvocationHandler invocationHandler = new ServiceInvocationHandler(serviceApiImp);
    //调用Proxy的newProxyInstance方法,传入接口的classLoader和interface类
    //还有invocationHandler 
    //这时候得到的是一个ServiceApi 实例
    ServiceApi proxyServiceApi = (ServiceApi) Proxy.newProxyInstance(ServiceApi.class.getClassLoader(), new Class<?>[]{ServiceApi.class},invocationHandler);
    //调用它的两个方法
    proxyServiceApi.login();
    proxyServiceApi.loginOut();
    

    得到打印信息:

    2021-07-18 18:12:55.592 5991-5991/com.example.rxjavaex2 D/TAG: 执行了invoke
    2021-07-18 18:12:55.592 5991-5991/com.example.rxjavaex2 D/TAG: 登录了
    2021-07-18 18:12:55.592 5991-5991/com.example.rxjavaex2 D/TAG: 执行了invoke
    2021-07-18 18:12:55.592 5991-5991/com.example.rxjavaex2 D/TAG: 退出登录了
    

    从效果来看,利用动态代理生成的那个ServiceApi实例在调用自身方法的时候看来实际执行了是传入的那个InvocationHandler里的那个invoke()方法:

      public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            Log.d("TAG","执行了invoke");
            //执行传入的serviceApi的method,
            return method.invoke(serviceApi,args);
        }
    

    即invoke()方法既执行了代理的ServiceApi实例的方法,同时也执行了自身的代码,而且这个规则对所有的ServiceApi里的方法都是有效的。

    带着这个疑问,我们来看看它是怎么做到的,其实从那个Proxy的newProxyInstance()方法我们可以肯定这里构建了一个ServiceApi的实现类,也就是我们要的代理类,并且new了一个它的实例对象,至于这个实现类长什么样子,我们继续看newProxyInstance(ClassLoader loader,Class<?>[] interfaces,InvocationHandler h)方法:
     public static Object newProxyInstance(ClassLoader loader,Class<?>[] interfaces,InvocationHandler h)throws IllegalArgumentException{
            Objects.requireNonNull(h);
    
            final Class<?>[] intfs = interfaces.clone();
            /*
             * Look up or generate the designated proxy class.
              查找或者生成指定的代理类
             */
            //这个是关键的步骤,注意,就是在这里生成的代理类
            Class<?> cl = getProxyClass0(loader, intfs);
    
            try {
                //拿到代理类的构造方法,这是一个入参为InvocationHandler的构造方法
                final Constructor<?> cons = cl.getConstructor(constructorParams);
                final InvocationHandler ih = h;
                //判断权限
                if (!Modifier.isPublic(cl.getModifiers())) {
                    cons.setAccessible(true);
                }
                //最终通过这个构造方法传入InvocationHandler创建了实例
                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数组的构造方法,并且就是用这个构造方法创建了实例。

    接下来继续追踪那个构建代理类的方法:

      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
    //翻译上面的注释:如果这个通过实现了给定的接口的给定的classLoader定义的代理类是存
    //在的,则会返回一个缓存复制品,否则会通过ProxyClassFactory来创建它
            return proxyClassCache.get(loader, interfaces);
        }
    

    proxyClassCache是个缓存工具,这里不深究它,直接看看代理类工厂ProxyClassFactory:

        /**
         * A factory function that generates, defines and returns the proxy class given
         * the ClassLoader and array of interfaces.
         *一个生成,定义,返回给定的classLoader和接口数组的代理类的工厂
         */
    //这是Proxy的内部类,主要看apply()方法
    
        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) {
                        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 the default package.
                    proxyPkg = "";
                }
    
                {
                    // Android-changed: Generate the proxy directly instead of calling
                    // through to ProxyGenerator.
                    List<Method> methods = getMethods(interfaces);
                    Collections.sort(methods, ORDER_BY_SIGNATURE_AND_SUBTYPE);
                    validateReturnTypes(methods);
                    List<Class<?>[]> exceptions = deduplicateAndGetExceptions(methods);
    
                    Method[] methodsArray = methods.toArray(new Method[methods.size()]);
                    Class<?>[][] exceptionsArray = exceptions.toArray(new Class<?>[exceptions.size()][]);
    
                    /*
                     * Choose a name for the proxy class to generate.
                     */
                    long num = nextUniqueNumber.getAndIncrement();
                    String proxyName = proxyPkg + proxyClassNamePrefix + num;
                    //最终把这些参数丢到这个方法里
                    return generateProxy(proxyName, interfaces, loader, methodsArray,
                                         exceptionsArray);
                }
            }
        }
    
    //我这个版本是个本地方法,看不到具体实现了- -尴尬了
     private static native Class<?> generateProxy(String name, Class<?>[] interfaces,
                                                     ClassLoader loader, Method[] methods,
                                                     Class<?>[][] exceptions);
    

    很不幸,分析到这里看不下去了,看来只能去网上找找看生成的那个代理类长什么样了,找了一圈发现有很多,结合自己的例子改了改:

    
    // 继承了Proxy类
    public final class $Proxy0 extends Proxy implements ServiceApi {
        private static Method m1;
        private static Method m8;
        private static Method m2;
        private static Method m3;
        private static Method m5;
        private static Method m4;
        private static Method m7;
        private static Method m9;
        private static Method m0;
        private static Method m6;
        //构造函数,入参是InvocationHandler 
        public $Proxy0(InvocationHandler var1) throws  {
            super(var1);
        }
    
    ....
    ....
    
    /**
    * 这里是代理类实现的被代理对象的接口的相同方法
    */
        public final void login() throws  {
            try {
                // super.h 对应的是父类的h变量,他就是Proxy.nexInstance方法中的InvocationHandler参数
               // 所以这里实际上就是使用了我们自己写的InvocationHandler实现类的invoke方法
                super.h.invoke(this, m3, new Object[]{var1});
            } catch (RuntimeException | Error var3) {
                throw var3;
            } catch (Throwable var4) {
                throw new UndeclaredThrowableException(var4);
            }
        }
        public final void loginOut() throws  {
            try {
                //可见logOut跟login都是一样的实现
             
                super.h.invoke(this, m3, new Object[]{var1});
            } catch (RuntimeException | Error var3) {
                throw var3;
            } catch (Throwable var4) {
                throw new UndeclaredThrowableException(var4);
            }
        }
    
       
    
       public final Class getClass() throws  {
            try {
                return (Class)super.h.invoke(this, m7, (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"));
                m8 = Class.forName("com.gwf.jdkproxy.ProductServiceImpl").getMethod("notify");
                m2 = Class.forName("java.lang.Object").getMethod("toString");
                m3 = Class.forName("com.gwf.jdkproxy.ProductServiceImpl").getMethod("login");
    m4= Class.forName("com.gwf.jdkproxy.ProductServiceImpl").getMethod("loginOut");
                m5 = Class.forName("com.gwf.jdkproxy.ProductServiceImpl").getMethod("wait", Long.TYPE);
             
                m7 = Class.forName("com.gwf.jdkproxy.ProductServiceImpl").getMethod("getClass");
                m9 = Class.forName("com.gwf.jdkproxy.ProductServiceImpl").getMethod("notifyAll");
                m0 = Class.forName("java.lang.Object").getMethod("hashCode");
                m6 = Class.forName("com.gwf.jdkproxy.ProductServiceImpl").getMethod("wait");
            } catch (NoSuchMethodException var2) {
                throw new NoSuchMethodError(var2.getMessage());
            } catch (ClassNotFoundException var3) {
                throw new NoClassDefFoundError(var3.getMessage());
            }
        }
    }
    

    看到这里应该豁然开朗了吧,其实很多听起来牛逼的技术术语,归根结底都是很原始的实现。

    相关文章

      网友评论

        本文标题:jdk动态代理原理解析

        本文链接:https://www.haomeiwen.com/subject/otrapltx.html