java动态代理

java动态代理

Posted by CHuiL on January 4, 2021

代理是基本的设计模式之一,为提供额外的或不同的操作,而插入的用来代替“实际”对象的对象。设计模式的关键就是封装修改。 动态代理即可以动态地创建代理并动态地处理对所代理方法的调用。使用动态代理,对象所有的调用都会被重定向到单一的调用处理器上

JDK动态代理

//调用接口
public interface Interface {
    void doSomething();
    void somethingElse(String arg);
}


//接口实现
public class RealObject implements Interface {

    @Override
    public void doSomething() {
        System.out.println("doSomething");
    }

    @Override
    public void somethingElse(String arg) {
        System.out.println("somethingElse "+arg);
    }
}

//简单的静态代理实现
class SimpleProxy implements Interface{
    private Interface proxy;
    public SimpleProxy(Interface proxied){
        this.proxy = proxied;
    }

    @Override
    public void somethingElse(String arg) {
        System.out.println("SimpleProxy somethingElse " + arg);
        proxy.somethingElse(arg);
    }

    @Override
    public void doSomething(){
        System.out.println("SimpleProxy doSomething");
        proxy.doSomething();
    }
}

//动态代理处理类,实现InvocationHandler接口
class DynamicProxyHandler implements InvocationHandler{
    private Object proxied;

    public DynamicProxyHandler(Object proxied){
        this.proxied = proxied;
    }


    @Override 
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println("**** proxy : " + proxy.getClass() + ", method: " + method + ", args: " + args);
        if (args != null){
            for (Object arg : args){
                System.out.println(" " + arg);
            }
        }
        System.out.println("我是代理");
        return method.invoke(proxied,args);
    }
}


class SimpleProxyDemoProxy{
    public static void consumer(Interface iface){
        iface.doSomething();
        iface.somethingElse("bonobo");
    }

    public static void main(String[] args){
//        consumer(new RealObject());
//        consumer(new SimpleProxy(new RealObject())); //简单静态代理
        RealObject real = new RealObject();
        consumer(real);
        Interface proxy = (Interface) Proxy.newProxyInstance(
                Interface.class.getClassLoader(),
                new Class[] {Interface.class},
                new DynamicProxyHandler(real)
        );
//        consumer(proxy);
        proxy.doSomething(); //调用方法会动态的进入invoke方法中,实现代理。
        proxy.somethingElse("ala");
        System.out.println(proxy.getClass().getSuperclass().getName());
        System.out.println(proxy.getClass().getName());
    }
}

结果

doSomething
somethingElse bonobo
**** proxy : class com.sun.proxy.$Proxy0, method: public abstract void interFace.Interface.doSomething(), args: null
我是代理
doSomething
**** proxy : class com.sun.proxy.$Proxy0, method: public abstract void interFace.Interface.somethingElse(java.lang.String), args: [Ljava.lang.Object;@4b67cf4d
 ala
我是代理
somethingElse ala
java.lang.reflect.Proxy
com.sun.proxy.$Proxy0

可以使用实现动态代理处理函数,来返回一个接口对象,每次对该对象进行方法调用,就会动态的进入到单一的调用处理函数,在里面实现调用,不过因为是单一处理函数,所以需要注意传入的参数。如果想对某一部分方法进行代理,可以通过参数或者方法名等手段来进行筛选。

JDK动态必须满足被代理对象要==实现接口==,否则无法代理,并且实现了接口,类上==非接口的定义==的方法也无法被代理; 从上面的newProxyInstance的参数我们也可以知道,他在创建代理对象的时候是需要接口信息的,并且将最终返回代理对象并向上转型为该接口;而他内部就只是为接口的所有创建代理方法,并且调用我们实现了==InvocationHandler==接口中的==invoke==方法;并且最终返回的代理对象是==Proxy==类的子类;

  • jdk主要利用反射来生成代理类;并且通过反射机制回调invoke方法,==方法执行效率==会比较低;

源码分析

我们深入newProxyInstance里面去了解一下
java.lang.reflect Proxy

   public static Object newProxyInstance(ClassLoader loader,
                                          Class<?>[] interfaces,
                                          InvocationHandler h) throws IllegalArgumentException
    {
        
        final Class<?>[] intfs = interfaces.clone();
        
        /*
         * Look up or generate the designated proxy class.
         */
        Class<?> cl = getProxyClass0(loader, intfs);
        
        ...
        //获取代理类构造函数
        final Constructor<?> cons = cl.getConstructor(constructorParams);
        final InvocationHandler ih = h;
        ...
        //实例化代理类对象
        return cons.newInstance(new Object[]{h});
        
    }

在进入getProxyClass0

    private static Class<?> getProxyClass0(ClassLoader loader,
                                           Class<?>... interfaces) {
        ...
        //如果该代理类实例已存在,则从缓存中返回,否则将通过ProxyClassFactory创建代理类
        return proxyClassCache.get(loader, interfaces);
    }

进入proxyClassCache.get

    public V get(K key, P parameter) {
        ...
        //
        while (true) {
            if (supplier != null) {
                //supplier 可能是个Factory 或者是CacheValue<V> 实例,也就是缓存中有,从缓存中获取,没有则从Factory中生成;
                V value = supplier.get();
                if (value != null) {
                    return value;
                }
            }

            
            // lazily construct a Factory
            if (factory == null) {
                factory = new Factory(key, parameter, subKey, valuesMap);
            }

            if (supplier == null) {
                supplier = valuesMap.putIfAbsent(subKey, factory);
                if (supplier == null) {
                    // successfully installed Factory
                    supplier = factory;
                }
            } else {
                .....
            }
        }
    }

进入Factory.get()

    public synchronized V get() { 
        ...
        // create new value
        V value = null;
        try {
            //这里的valueFactory就是ProxyClassFactory()
            value = Objects.requireNonNull(valueFactory.apply(key, parameter));
        } finally {
            ....
        }
        //中间设置缓存的过程

        // successfully replaced us with new CacheValue -> return the value
        // wrapped by it
        return value;
    }

进入ProxyClassFactory.apply

        public Class<?> apply(ClassLoader loader, Class<?>[] interfaces) {

            for (Class<?> intf : interfaces) {
                //检查class loader和interfaces Class name是否一直
                //检查Class是否是一个interface
                //Verify that this interface is not a duplicate.
            }
            
            //设置代理类名
            long num = nextUniqueNumber.getAndIncrement();
            String proxyName = proxyPkg + proxyClassNamePrefix + num; //"$Proxy"

            //生成指定代理类字节码
            byte[] proxyClassFile = ProxyGenerator.generateProxyClass(
                proxyName, interfaces, accessFlags);
            
            ...
            //根据字节码加载代理类
            return defineClass0(loader, proxyName,proxyClassFile, 0, proxyClassFile.length);
        }
    }

defineClass0是一个native类,就不在往下看了; 我们可以利用ProxyGenerator.generateProxyClass这个方法来生成对应字节码,在反编译为源码;查看一下这个神秘的代理类长什么样子


public final class testInterface0 extends Proxy implements Interface {
    private static Method m1;
    private static Method m3;
    private static Method m2;
    private static Method m4;
    private static Method m0;

    public testInterface0(InvocationHandler var1) throws  {
        super(var1);
    }

    public final boolean equals(Object var1) throws  {
        try {
            return (Boolean)super.h.invoke(this, m1, new Object[]{var1});
        } catch (RuntimeException | Error var3) {
            throw var3;
        } catch (Throwable var4) {
            throw new UndeclaredThrowableException(var4);
        }
    }

    public final void doSomething() throws  {
        try {
            super.h.invoke(this, m3, (Object[])null);
        } catch (RuntimeException | Error var2) {
            throw var2;
        } catch (Throwable var3) {
            throw new UndeclaredThrowableException(var3);
        }
    }

    public final String toString() throws  {
        try {
            return (String)super.h.invoke(this, m2, (Object[])null);
        } catch (RuntimeException | Error var2) {
            throw var2;
        } catch (Throwable var3) {
            throw new UndeclaredThrowableException(var3);
        }
    }

    public final void somethingElse(String var1) throws  {
        try {
            super.h.invoke(this, m4, new Object[]{var1});
        } catch (RuntimeException | Error var3) {
            throw var3;
        } catch (Throwable var4) {
            throw new UndeclaredThrowableException(var4);
        }
    }

    public final int hashCode() throws  {
        try {
            return (Integer)super.h.invoke(this, m0, (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"));
            m3 = Class.forName("com.company.jdkProxy.TestJDKProxy$Interface").getMethod("doSomething");
            m2 = Class.forName("java.lang.Object").getMethod("toString");
            m4 = Class.forName("com.company.jdkProxy.TestJDKProxy$Interface").getMethod("somethingElse", Class.forName("java.lang.String"));
            m0 = Class.forName("java.lang.Object").getMethod("hashCode");
        } catch (NoSuchMethodException var2) {
            throw new NoSuchMethodError(var2.getMessage());
        } catch (ClassNotFoundException var3) {
            throw new NoClassDefFoundError(var3.getMessage());
        }
    }
}

CGLib

CGLib使用ASM字节码框架,直接对需要代理的类的字节码进行操作,生成该类的一个子类,并且重新所有方法,在重写的过程中加入我们的代理逻辑,并调用原来类的方法。
这种实现方法就不要求类需要实现接口了;

  • 这种方式生成的类,与自己编写并编译的静态代理类没有什么太大区别,对方法的调用也与直接调用普通类的方式一致,所有比JDK的方式效率要更高;
  • 由于代理的方式是继承,如果被代理类是一个final类,则无法使用CGLib代理
  • 由于需要重新父类方法,所以无法给final方法,或者private方法进行代理,因为子类无法重写这些方法;
  • CGLib是通过操作字节码的,这种==生成代理类的速度==要比JDK通过反射 生成代理类的速度==更慢==;

写写代码看看,Cglib写起来其实和JDK类似,只是少一步接口,这里需要实现类InvocationHandler的接口MethodInterceptor作为回调;


public class RealToll  {
    public void doSomething() {
        System.out.println("doSomething");
    }

    public void somethingElse(String arg) {
        System.out.println("somethingElse "+arg);
    }
}

private static void testCglibProxy() throws Exception {
    RealToll realToll = new RealToll();
    Enhancer enhancer = new Enhancer();
    enhancer.setSuperclass(RealToll.class);//设置父类
    //设置回调,类似jdk里面InvocationHandler
    Callback realCallback = new MethodInterceptor() { 
        @Override
        public Object intercept(Object o, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
            System.out.println("cglib proxy invoke "+method.getName()+" begin");
            Object result = methodProxy.invokeSuper(o,args);
            System.out.println("cglib proxy invoke end");
            return result;
        }
    };
    enhancer.setCallback(realCallback);
    RealToll proxyRealToll = (RealToll) enhancer.create();
    proxyRealToll.doSomething();
    proxyRealToll.somethingElse("cglib real tool test");
    byte[] cglibProxyClassFile = enhancer.getStrategy().generate(enhancer);

    System.out.println("get proxy class name "+proxyRealToll.getClass().getName());
    System.out.println("get proxy class super class name "+ proxyRealToll.getClass().getSuperclass().getName());

    try {
        FileOutputStream fileOutputStream = new FileOutputStream("TestCglibRealTollProxy0.class");
        fileOutputStream.write(cglibProxyClassFile);
        fileOutputStream.flush();
        fileOutputStream.close();
    }catch (Exception e){
        System.out.println(e);
    }
}

返回结果

cglib proxy invoke doSomething begin
doSomething
cglib proxy invoke end
cglib proxy invoke somethingElse begin
somethingElse cglib real tool test
cglib proxy invoke end
get proxy class name com.test.demo.proxy.RealToll$$EnhancerByCGLIB$$e5f2d5f2
get proxy class super class name com.test.demo.proxy.RealToll

通过获取生成的字节码反编译看看代理源码类


public class RealToll$$EnhancerByCGLIB$$e5f2d5f2 extends RealToll implements Factory {
    private boolean CGLIB$BOUND;
    public static Object CGLIB$FACTORY_DATA;
    private static final ThreadLocal CGLIB$THREAD_CALLBACKS;
    private static final Callback[] CGLIB$STATIC_CALLBACKS;
    private MethodInterceptor CGLIB$CALLBACK_0;
    private static Object CGLIB$CALLBACK_FILTER;
    private static final Method CGLIB$somethingElse$0$Method;
    private static final MethodProxy CGLIB$somethingElse$0$Proxy;
    private static final Object[] CGLIB$emptyArgs;
    private static final Method CGLIB$doSomething$1$Method;
    private static final MethodProxy CGLIB$doSomething$1$Proxy;
    private static final Method CGLIB$equals$2$Method;
    private static final MethodProxy CGLIB$equals$2$Proxy;
    private static final Method CGLIB$toString$3$Method;
    private static final MethodProxy CGLIB$toString$3$Proxy;
    private static final Method CGLIB$hashCode$4$Method;
    private static final MethodProxy CGLIB$hashCode$4$Proxy;
    private static final Method CGLIB$clone$5$Method;
    private static final MethodProxy CGLIB$clone$5$Proxy;

    static void CGLIB$STATICHOOK2() {
        CGLIB$THREAD_CALLBACKS = new ThreadLocal();
        CGLIB$emptyArgs = new Object[0];
        Class var0 = Class.forName("com.test.demo.proxy.RealToll$$EnhancerByCGLIB$$e5f2d5f2");
        Class var1;
        Method[] var10000 = ReflectUtils.findMethods(new String[]{"equals", "(Ljava/lang/Object;)Z", "toString", "()Ljava/lang/String;", "hashCode", "()I", "clone", "()Ljava/lang/Object;"}, (var1 = Class.forName("java.lang.Object")).getDeclaredMethods());
        CGLIB$equals$2$Method = var10000[0];
        CGLIB$equals$2$Proxy = MethodProxy.create(var1, var0, "(Ljava/lang/Object;)Z", "equals", "CGLIB$equals$2");
        CGLIB$toString$3$Method = var10000[1];
        CGLIB$toString$3$Proxy = MethodProxy.create(var1, var0, "()Ljava/lang/String;", "toString", "CGLIB$toString$3");
        CGLIB$hashCode$4$Method = var10000[2];
        CGLIB$hashCode$4$Proxy = MethodProxy.create(var1, var0, "()I", "hashCode", "CGLIB$hashCode$4");
        CGLIB$clone$5$Method = var10000[3];
        CGLIB$clone$5$Proxy = MethodProxy.create(var1, var0, "()Ljava/lang/Object;", "clone", "CGLIB$clone$5");
        var10000 = ReflectUtils.findMethods(new String[]{"somethingElse", "(Ljava/lang/String;)V", "doSomething", "()V"}, (var1 = Class.forName("com.test.demo.proxy.RealToll")).getDeclaredMethods());
        CGLIB$somethingElse$0$Method = var10000[0];
        CGLIB$somethingElse$0$Proxy = MethodProxy.create(var1, var0, "(Ljava/lang/String;)V", "somethingElse", "CGLIB$somethingElse$0");//创建MethodProxy代理,是为了能够直接调用原类的方法,而不是通过反射(method.invoker)
        CGLIB$doSomething$1$Method = var10000[1];
        CGLIB$doSomething$1$Proxy = MethodProxy.create(var1, var0, "()V", "doSomething", "CGLIB$doSomething$1");
    }
    //原调用函数封装
    final void CGLIB$somethingElse$0(String var1) {
        super.somethingElse(var1);
    }
    //重新父类方法
    public final void somethingElse(String var1) {
        MethodInterceptor var10000 = this.CGLIB$CALLBACK_0;
        if (var10000 == null) {
            CGLIB$BIND_CALLBACKS(this);
            var10000 = this.CGLIB$CALLBACK_0;
        }

        if (var10000 != null) {
            var10000.intercept(this, CGLIB$somethingElse$0$Method, new Object[]{var1}, CGLIB$somethingElse$0$Proxy);//调用拦截器
        } else {
            super.somethingElse(var1);
        }
    }

    final void CGLIB$doSomething$1() {
        super.doSomething();
    }

    public final void doSomething() {
        MethodInterceptor var10000 = this.CGLIB$CALLBACK_0;
        if (var10000 == null) {
            CGLIB$BIND_CALLBACKS(this);
            var10000 = this.CGLIB$CALLBACK_0;
        }

        if (var10000 != null) {
            var10000.intercept(this, CGLIB$doSomething$1$Method, CGLIB$emptyArgs, CGLIB$doSomething$1$Proxy);
        } else {
            super.doSomething();
        }
    }

    final boolean CGLIB$equals$2(Object var1) {
        return super.equals(var1);
    }

    public final boolean equals(Object var1) {
        MethodInterceptor var10000 = this.CGLIB$CALLBACK_0;
        if (var10000 == null) {
            CGLIB$BIND_CALLBACKS(this);
            var10000 = this.CGLIB$CALLBACK_0;
        }

        if (var10000 != null) {
            Object var2 = var10000.intercept(this, CGLIB$equals$2$Method, new Object[]{var1}, CGLIB$equals$2$Proxy);
            return var2 == null ? false : (Boolean)var2;
        } else {
            return super.equals(var1);
        }
    }

    final String CGLIB$toString$3() {
        return super.toString();
    }

    public final String toString() {
        MethodInterceptor var10000 = this.CGLIB$CALLBACK_0;
        if (var10000 == null) {
            CGLIB$BIND_CALLBACKS(this);
            var10000 = this.CGLIB$CALLBACK_0;
        }

        return var10000 != null ? (String)var10000.intercept(this, CGLIB$toString$3$Method, CGLIB$emptyArgs, CGLIB$toString$3$Proxy) : super.toString();
    }

    final int CGLIB$hashCode$4() {
        return super.hashCode();
    }

    public final int hashCode() {
        MethodInterceptor var10000 = this.CGLIB$CALLBACK_0;
        if (var10000 == null) {
            CGLIB$BIND_CALLBACKS(this);
            var10000 = this.CGLIB$CALLBACK_0;
        }

        if (var10000 != null) {
            Object var1 = var10000.intercept(this, CGLIB$hashCode$4$Method, CGLIB$emptyArgs, CGLIB$hashCode$4$Proxy);
            return var1 == null ? 0 : ((Number)var1).intValue();
        } else {
            return super.hashCode();
        }
    }

    final Object CGLIB$clone$5() throws CloneNotSupportedException {
        return super.clone();
    }

    protected final Object clone() throws CloneNotSupportedException {
        MethodInterceptor var10000 = this.CGLIB$CALLBACK_0;
        if (var10000 == null) {
            CGLIB$BIND_CALLBACKS(this);
            var10000 = this.CGLIB$CALLBACK_0;
        }

        return var10000 != null ? var10000.intercept(this, CGLIB$clone$5$Method, CGLIB$emptyArgs, CGLIB$clone$5$Proxy) : super.clone();
    }

    public static MethodProxy CGLIB$findMethodProxy(Signature var0) {
        String var10000 = var0.toString();
        switch(var10000.hashCode()) {
        case -2123282676:
            if (var10000.equals("somethingElse(Ljava/lang/String;)V")) {
                return CGLIB$somethingElse$0$Proxy;
            }
            break;
        case -508378822:
            if (var10000.equals("clone()Ljava/lang/Object;")) {
                return CGLIB$clone$5$Proxy;
            }
            break;
        case 1826985398:
            if (var10000.equals("equals(Ljava/lang/Object;)Z")) {
                return CGLIB$equals$2$Proxy;
            }
            break;
        case 1913648695:
            if (var10000.equals("toString()Ljava/lang/String;")) {
                return CGLIB$toString$3$Proxy;
            }
            break;
        case 1984935277:
            if (var10000.equals("hashCode()I")) {
                return CGLIB$hashCode$4$Proxy;
            }
            break;
        case 2121560294:
            if (var10000.equals("doSomething()V")) {
                return CGLIB$doSomething$1$Proxy;
            }
        }

        return null;
    }

    public RealToll$$EnhancerByCGLIB$$e5f2d5f2() {
        CGLIB$BIND_CALLBACKS(this);
    }

    public static void CGLIB$SET_THREAD_CALLBACKS(Callback[] var0) {
        CGLIB$THREAD_CALLBACKS.set(var0);
    }

    public static void CGLIB$SET_STATIC_CALLBACKS(Callback[] var0) {
        CGLIB$STATIC_CALLBACKS = var0;
    }

    private static final void CGLIB$BIND_CALLBACKS(Object var0) {
        RealToll$$EnhancerByCGLIB$$e5f2d5f2 var1 = (RealToll$$EnhancerByCGLIB$$e5f2d5f2)var0;
        if (!var1.CGLIB$BOUND) {
            var1.CGLIB$BOUND = true;
            Object var10000 = CGLIB$THREAD_CALLBACKS.get();
            if (var10000 == null) {
                var10000 = CGLIB$STATIC_CALLBACKS;
                if (var10000 == null) {
                    return;
                }
            }

            var1.CGLIB$CALLBACK_0 = (MethodInterceptor)((Callback[])var10000)[0];
        }

    }

    public Object newInstance(Callback[] var1) {
        CGLIB$SET_THREAD_CALLBACKS(var1);
        RealToll$$EnhancerByCGLIB$$e5f2d5f2 var10000 = new RealToll$$EnhancerByCGLIB$$e5f2d5f2();
        CGLIB$SET_THREAD_CALLBACKS((Callback[])null);
        return var10000;
    }

    public Object newInstance(Callback var1) {
        CGLIB$SET_THREAD_CALLBACKS(new Callback[]{var1});
        RealToll$$EnhancerByCGLIB$$e5f2d5f2 var10000 = new RealToll$$EnhancerByCGLIB$$e5f2d5f2();
        CGLIB$SET_THREAD_CALLBACKS((Callback[])null);
        return var10000;
    }

    public Object newInstance(Class[] var1, Object[] var2, Callback[] var3) {
        CGLIB$SET_THREAD_CALLBACKS(var3);
        RealToll$$EnhancerByCGLIB$$e5f2d5f2 var10000 = new RealToll$$EnhancerByCGLIB$$e5f2d5f2;
        switch(var1.length) {
        case 0:
            var10000.<init>();
            CGLIB$SET_THREAD_CALLBACKS((Callback[])null);
            return var10000;
        default:
            throw new IllegalArgumentException("Constructor not found");
        }
    }

    public Callback getCallback(int var1) {
        CGLIB$BIND_CALLBACKS(this);
        MethodInterceptor var10000;
        switch(var1) {
        case 0:
            var10000 = this.CGLIB$CALLBACK_0;
            break;
        default:
            var10000 = null;
        }

        return var10000;
    }

    public void setCallback(int var1, Callback var2) {
        switch(var1) {
        case 0:
            this.CGLIB$CALLBACK_0 = (MethodInterceptor)var2;
        default:
        }
    }

    public Callback[] getCallbacks() {
        CGLIB$BIND_CALLBACKS(this);
        return new Callback[]{this.CGLIB$CALLBACK_0};
    }

    public void setCallbacks(Callback[] var1) {
        this.CGLIB$CALLBACK_0 = (MethodInterceptor)var1[0];
    }

    static {
        CGLIB$STATICHOOK2();
    }
}

可以看到,代理类继承了RealTool,实现了Factory接口;
这里有个小细节,就是他在调用原函数的不是像JDK那样利用反射(在invocationHandler中用method.invoke),而是用MethodProxy.invokeSuper。他生成的代理里中,有对原函数的一个封装,用它来构造MethodProxy,里面会将该method引用保存起来,调用的时候直接调用该函数

    public Object invokeSuper(Object obj, Object[] args) throws Throwable {
        try {
            this.init();
            MethodProxy.FastClassInfo fci = this.fastClassInfo;
            return fci.f2.invoke(fci.i2, obj, args);
        } catch (InvocationTargetException var4) {
            throw var4.getTargetException();
        }
    }

参考

浅析Spring中AOP的实现原理——动态代理 通过反编译后的字节码理解cglib代理