美文网首页我爱编程Java
浅析jdk动态代理proxy的调用过程

浅析jdk动态代理proxy的调用过程

作者: 打伞的Fish | 来源:发表于2018-07-21 11:38 被阅读1次

    通过这篇文章你会知道如下:

    • 动态代理如何实现?
    • 代理对象与真实对象之间是什么关系?
    • 通过代理对象的调用,invocationHandler中的invoke方法是如何被调用的

    目前尚未厘清字节码是如何生成,代理对象中的方法体是如何写入的?

    动态代理就是将代理插入到客户和目标之间,从而为客户和目标对象之间引入一定的间接性,这个间接性就可以给代理提供很多的活动空间,代理可以在调用目标对象的前后做些通知操作,从而实现新的功能或者扩展目标对象的功能;

    • 动态代理常规写法例子:
    man--接口
    boss--实现类
    代理
    代理工厂--产生代理对象
    测试
    • 调用过程分析

    从上面的例子得知,proxy是通过Proxy.newProxyInstance产生的,此时就有如下疑问:

    1. 调用proxy.doSomething时候,内部是如何调用到invoke方法?
    2. 参数interface作用是啥?
      下面就开始分析这些疑问
      下面这张图说明,代理对象是通过getProxyClass0方法产生的,最后通过newIntstance实例化,同时传入invokehandler对象
      Proxy.newProxyInstance

    下图说明代理对象的产生最终会落到proxyClassFactory中,注释也有说明这点,但是具体为什么会落到proxyClassFactory,你打个断点跟踪会,自然而然就知道了。所以现在的重点就在proxyClassFactory里面是如何产生对象的?

    getProxyClass0方法
     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 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());
            }
        }
    }
    

    proxyClassFactory类中可以看到代理对象产生的名字构成过程,同时会处理如果实现的接口访问权限不是public的情况;

    String proxyName = proxyPkg + proxyClassNamePrefix + num;
    

    生成代理对象的过程在这段代码里面,真正产生队里对象的类是ProxyGenerator.generateClassFile方法


    代理对象产生
    代理对象的方法构建过程

    最终生成的代理对象如下,可以发现在doSomething方法中,发现是调用了h.invokerhandler的invoke方法,这个h对象则是父类Proxy中的属性,通过构造方法进行对象赋值;所以就可以解释最初的疑问了。

    另外要获取这个对象的反编译的源码,需要改变sun.misc.ProxyGenerator.saveGeneratedFiles参数,才能写入到硬盘,具体为什么是true,在ProxyGenerator.generateProxyClass方法中可以看到原因。
    System.getProperties().put("sun.misc.ProxyGenerator.saveGeneratedFiles", "true");

    package com.sun.proxy;
    
    import com.example.proxy.Man;
    
    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 Man {
    private static Method m1;
    private static Method m3;
    private static Method m2;
    private static Method m0;
    
    public $Proxy0(InvocationHandler paramInvocationHandler)
            throws {
        super(paramInvocationHandler);
    }
    
    public final boolean equals(Object paramObject)
            throws {
        try {
            return ((Boolean) this.h.invoke(this, m1, new Object[]{paramObject})).booleanValue();
        } catch (Error | RuntimeException localError) {
            throw localError;
        } catch (Throwable localThrowable) {
            throw new UndeclaredThrowableException(localThrowable);
        }
    }
    
    public final void doSomething()
            throws {
        try {
            this.h.invoke(this, m3, null);
            return;
        } catch (Error | RuntimeException localError) {
            throw localError;
        } catch (Throwable localThrowable) {
            throw new UndeclaredThrowableException(localThrowable);
        }
    }
    
    public final String toString()
            throws {
        try {
            return (String) this.h.invoke(this, m2, null);
        } catch (Error | RuntimeException localError) {
            throw localError;
        } catch (Throwable localThrowable) {
            throw new UndeclaredThrowableException(localThrowable);
        }
    }
    
    public final int hashCode()
            throws {
        try {
            return ((Integer) this.h.invoke(this, m0, null)).intValue();
        } catch (Error | RuntimeException localError) {
            throw localError;
        } catch (Throwable localThrowable) {
            throw new UndeclaredThrowableException(localThrowable);
        }
    }
    
    static {
        try {
            m1 = Class.forName("java.lang.Object").getMethod("equals", new Class[]{Class.forName("java.lang.Object")});
            m3 = Class.forName("com.example.proxy.Man").getMethod("doSomething", new Class[0]);
            m2 = Class.forName("java.lang.Object").getMethod("toString", new Class[0]);
            m0 = Class.forName("java.lang.Object").getMethod("hashCode", new Class[0]);
            return;
        } catch (NoSuchMethodException localNoSuchMethodException) {
            throw new NoSuchMethodError(localNoSuchMethodException.getMessage());
        } catch (ClassNotFoundException localClassNotFoundException) {
            throw new NoClassDefFoundError(localClassNotFoundException.getMessage());
        }
    }
    

    }

    相关文章

      网友评论

        本文标题:浅析jdk动态代理proxy的调用过程

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