Java--动态代理Method源码分析

在使用动态代理时,要实现接口 InvocationHandler,当我们通过代理对象调用一个方法的时候,这个方法的调用就会被转发为由InvocationHandler这个接口的 invoke 方法来进行调用,invoke方法需要传入method参数,即所要调用真实对象的某个方法的Method对象,当代理对象调用真实对象的方法时,其会自动的跳转到代理对象关联的handler对象的invoke方法来进行调用

    public Object invoke(Object proxy, Method method, Object[] args)
            throws Throwable {
        //当代理对象调用真实对象的方法时,其会自动的跳转到代理对象关联的handler对象的invoke方法来进行调用
        Object object = method.invoke(hello, args);
        return object;
    }

现在来分析一下method.invoke的源码
Method层级结构如下:


Java--动态代理Method源码分析_第1张图片
3951360-bded1ce08ec7945d.png
    @CallerSensitive
    public Object invoke(Object obj, Object... args)
        throws IllegalAccessException, IllegalArgumentException,
           InvocationTargetException
    {
    /*检查 AccessibleObject的override属性是否为true(override属性默认为false)
    * AccessibleObject是Method的父类
    * (Method extends Executable, Executable extends AccessibleObject),
    * 可调用setAccessible方法改变(setAccessible是AccessibleObject中的方法)
    * 如果override设置为true,则表示可以忽略访问权限的限制,直接调用。
    */
        if (!override) {
            //检查方法是否为public的
            if (!Reflection.quickCheckMemberAccess(clazz, modifiers)) {
                //获得到调用这个方法的Class
                Class caller = Reflection.getCallerClass();
                /*校验是否有访问权限,这个方法在AccessibleObject中,
                 *有缓存机制,如果下次还是这个类来调用就不用去做校验了,直接用上次的结果
                 *但是如果下次换一个类来调用,就会重新校验,
                 *因此这个缓存机制只适用于一个类的调用
                 */
                checkAccess(caller, clazz, obj, modifiers);
            }
        }
        MethodAccessor ma = methodAccessor;             // read volatile
        if (ma == null) {
            ma = acquireMethodAccessor();
        }
        return ma.invoke(obj, args);//返回MethodAccessor.invoke
    }

看一下有缓存机制的checkAccess

void checkAccess(Class caller, Class clazz, Object obj, int modifiers)
        throws IllegalAccessException
    {
        //可以看到,如果下一次的类和上次一致,直接返回上次结果
        if (caller == clazz) {  // quick check
            return;             // ACCESS IS OK
        }
       //从缓存中取得类
        Object cache = securityCheckCache;  // read volatile
        Class targetClass = clazz;
       //方法是protected,并且和上次的类不一致
        if (obj != null
            && Modifier.isProtected(modifiers)
            && ((targetClass = obj.getClass()) != clazz)) {
            // Must match a 2-list of { caller, targetClass }.
            if (cache instanceof Class[]) {
                Class[] cache2 = (Class[]) cache;
                if (cache2[1] == targetClass &&
                    cache2[0] == caller) {
                    return;     // ACCESS IS OK
                }
                // (Test cache[1] first since range check for [1]
                // subsumes range check for [0].)
            }
        } else if (cache == caller) {//返回缓存里的类
            // Non-protected case (or obj.class == this.clazz).
            return;             // ACCESS IS OK
        }

        // If no return, fall through to the slow path.
        //把结果记入缓存
        slowCheckMemberAccess(caller, clazz, obj, modifiers, targetClass);
    }

再看看acquireMethodAccessor这个方法

    private volatile MethodAccessor methodAccessor;

  private Method root;//每个Method对象包含一个root对象

    private MethodAccessor acquireMethodAccessor() {
        // First check to see if one has been created yet, and take it
        // if so
        MethodAccessor tmp = null;
        //root对象里持有一个MethodAccessor对象
        if (root != null) tmp = root.getMethodAccessor();
        if (tmp != null) {
            methodAccessor = tmp;
        } else {
            // Otherwise fabricate one and propagate it up to the root
            //如果MethodAccessor对象为null,就由reflectionFactory方法生成
            //这是一个native方法
            tmp = reflectionFactory.newMethodAccessor(this);
            setMethodAccessor(tmp);
        }

        return tmp;
    }

之后调用MethodAccessor的invoke方法

    public interface MethodAccessor {
    /** Matches specification in {@link java.lang.reflect.Method} */
    public Object invoke(Object obj, Object[] args)
        throws IllegalArgumentException, InvocationTargetException;
    }

可以看到它只是一个接口,这个invoke()方法与Method.invoke()的对应。创建MethodAccessor实例的是ReflectionFactory。

    sun.reflect.ReflectionFactory:
    public class ReflectionFactory {
    
        public MethodAccessor newMethodAccessor(Method method) {
            checkInitted();

            if (noInflation) {
                return new MethodAccessorGenerator().
                    generateMethod(method.getDeclaringClass(),
                                   method.getName(),
                                   method.getParameterTypes(),
                                   method.getReturnType(),
                                   method.getExceptionTypes(),
                                   method.getModifiers());
            } else {
                NativeMethodAccessorImpl acc =
                    new NativeMethodAccessorImpl(method);
                DelegatingMethodAccessorImpl res =
                    new DelegatingMethodAccessorImpl(acc);
                acc.setParent(res);
                return res;
            }
        }
    
    }

注释中写道:实际的MethodAccessor实现有两个版本,一个是Java实现的,另一个是native code实现的。Java实现的版本在初始化时需要较多时间,但长久来说性能较好;native版本正好相反,启动时相对较快,但运行时间长了之后速度就比不过Java版了。这是HotSpot虚拟机的优化方式带来的性能特性,同时也是许多虚拟机的共同点:跨越native边界会对优化有阻碍作用,它就像个黑箱一样让虚拟机难以分析也将其内联,于是运行时间长了之后反而是托管版本的代码更快些。
为了权衡两个版本的性能,Sun的JDK使用了“inflation”的技巧:让Java方法在被反射调用时,开头若干次使用native版,等反射调用次数超过阈值时则生成一个专用的MethodAccessor实现类,生成其中的invoke()方法的字节码,以后对该Java方法的反射调用就会使用Java版。
Sun的JDK是从1.4系开始采用这种优化的。
可以在启动命令里加上-Dsun.reflect.noInflation=true,就会RefactionFactory的noInflation属性就变成true了,这样不用等到15调用后,程序一开始就会用java版的MethodAccessor了。

在“开头若干次”时用到的DelegatingMethodAccessorImpl代码如下:

sun.reflect.DelegatingMethodAccessorImpl:
    /** Delegates its invocation to another MethodAccessorImpl and can
    change its delegate at run time. */

    class DelegatingMethodAccessorImpl extends MethodAccessorImpl {
        private MethodAccessorImpl delegate;

        DelegatingMethodAccessorImpl(MethodAccessorImpl delegate) {
            setDelegate(delegate);
        }    

        public Object invoke(Object obj, Object[] args)
            throws IllegalArgumentException, InvocationTargetException
        {
            return delegate.invoke(obj, args);
        }

        void setDelegate(MethodAccessorImpl delegate) {
            this.delegate = delegate;
        }
    }

native版MethodAccessor的Java一侧的声明:

sun.reflect.NativeMethodAccessorImpl:
    /** Used only for the first few invocations of a Method; afterward,
    switches to bytecode-based implementation */

    class NativeMethodAccessorImpl extends MethodAccessorImpl {
        private Method method;
        private DelegatingMethodAccessorImpl parent;
        private int numInvocations;

        NativeMethodAccessorImpl(Method method) {
            this.method = method;
        }    

        /*每次NativeMethodAccessorImpl.invoke()方法被调用时,都会使numInvocations++,
        * 当numInvocations>ReflectionFactory.inflationThreshold()(15次),
        * 则调用MethodAccessorGenerator.generateMethod()来生成Java版的MethodAccessor的实现类
        * 通过setDelegate来改变DelegatingMethodAccessorImpl所引用的MethodAccessor为Java版
        * 后续经由DelegatingMethodAccessorImpl.invoke()调用到的就是Java版的实现了。
        */
        public Object invoke(Object obj, Object[] args)
            throws IllegalArgumentException, InvocationTargetException
        {
            if (++numInvocations > ReflectionFactory.inflationThreshold()) {
                MethodAccessorImpl acc = (MethodAccessorImpl)
                    new MethodAccessorGenerator().
                        generateMethod(method.getDeclaringClass(),
                                       method.getName(),
                                       method.getParameterTypes(),
                                       method.getReturnType(),
                                       method.getExceptionTypes(),
                                       method.getModifiers());
                parent.setDelegate(acc);
            }
            
            return invoke0(method, obj, args);//native方法
        }

        void setParent(DelegatingMethodAccessorImpl parent) {
            this.parent = parent;
        }

        private static native Object invoke0(Method m, Object obj, Object[] args);
    }

你可能感兴趣的:(Java--动态代理Method源码分析)