CGLIB动态代理

知识回顾

在文章初识AOP中,了解到为什么要用代理,静态代理和动态代理的区别,在JDK的动态代理中讲到JDK的动态代理是如何实现的,有什么优缺点,本篇将继续聊下CGLIB中动态代理是如何实现的。

定义一个IHello的接口和一个Hello的实现类如下

package seven.com.seven.aop;

public interface IHello {

    void say();

}

package seven.com.seven.aop;

public class Hello implements IHello {

    @Override
    public void say() {
        System.out.println("hello word");
    }
}

CGLIB的动态代理类如下

package seven.com.seven.aop;

import net.sf.cglib.core.DebuggingClassWriter;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

public class DynamicCGLibProxy  implements MethodInterceptor {

    /**
     * 被代理对象
     */
    private Object target;


    public Object getProxy(Object target){
        // 代理类class文件存入本地磁盘方便我们反编译查看源码
        System.setProperty(DebuggingClassWriter.DEBUG_LOCATION_PROPERTY, "D:\\code");
        this.target=target;
        /**
         * 动态代码生成器
         */
        Enhancer enhancer=new Enhancer();
        enhancer.setSuperclass(target.getClass());
        enhancer.setCallback(this);

        /**
         * 动态生成字节码并返回代理对象
         */
        return enhancer.create();
    }

    @Override
    public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
        long star = System.currentTimeMillis();
        Object result = proxy.invokeSuper(obj,args);
        long end = System.currentTimeMillis();
        System.out.println(String.format("method cost %s", (end - star)));
        return result;
    }
}


package seven.com;

import seven.com.seven.aop.DynamicCGLibProxy;
import seven.com.seven.aop.DynamicJDKProxy;
import seven.com.seven.aop.Hello;
import seven.com.seven.aop.IHello;

public class App {
    public static void main(String[] args) {
        Hello hello = new Hello();
        IHello proxy = (IHello) new DynamicCGLibProxy().getProxy(hello);
        proxy.say();
    }
}

分析生成的代理类

通过设置参数System.setProperty(DebuggingClassWriter.DEBUG_LOCATION_PROPERTY, "D:\code");,可以把生成的代理类保存到磁盘中,我们可以在指定目录中看到自动生成的文件不止一个,反编译看下其中Hello类的代理类源码如下,如果耐着性子仔细分析下就不难看出,其实动态代理类是在静态构造函数中把每一个父类的方法分别对应创建了一个MethodProxy对象,也就是方法代理对象

//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package seven.com.seven.aop;

import java.lang.reflect.Method;
import net.sf.cglib.core.ReflectUtils;
import net.sf.cglib.core.Signature;
import net.sf.cglib.proxy.Callback;
import net.sf.cglib.proxy.Factory;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

public class Hello$$EnhancerByCGLIB$$f0ec8381 extends Hello 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$say$0$Method;
    private static final MethodProxy CGLIB$say$0$Proxy;
    private static final Object[] CGLIB$emptyArgs;
    private static final Method CGLIB$equals$1$Method;
    private static final MethodProxy CGLIB$equals$1$Proxy;
    private static final Method CGLIB$toString$2$Method;
    private static final MethodProxy CGLIB$toString$2$Proxy;
    private static final Method CGLIB$hashCode$3$Method;
    private static final MethodProxy CGLIB$hashCode$3$Proxy;
    private static final Method CGLIB$clone$4$Method;
    private static final MethodProxy CGLIB$clone$4$Proxy;

        /**
         * 这里是根据所继承的类(包括Object),查找出所有方法(非final),然后分别生成对应的MethodProxy对象,也就是方法的代理对象,最终传入到MethodInterceptor的intercept方法的最后一个参数中
         */
    static void CGLIB$STATICHOOK1() {
        CGLIB$THREAD_CALLBACKS = new ThreadLocal();
        CGLIB$emptyArgs = new Object[0];
        Class var0 = Class.forName("seven.com.seven.aop.Hello$$EnhancerByCGLIB$$f0ec8381");
        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$1$Method = var10000[0];
        CGLIB$equals$1$Proxy = MethodProxy.create(var1, var0, "(Ljava/lang/Object;)Z", "equals", "CGLIB$equals$1");
        CGLIB$toString$2$Method = var10000[1];
        CGLIB$toString$2$Proxy = MethodProxy.create(var1, var0, "()Ljava/lang/String;", "toString", "CGLIB$toString$2");
        CGLIB$hashCode$3$Method = var10000[2];
        CGLIB$hashCode$3$Proxy = MethodProxy.create(var1, var0, "()I", "hashCode", "CGLIB$hashCode$3");
        CGLIB$clone$4$Method = var10000[3];
        CGLIB$clone$4$Proxy = MethodProxy.create(var1, var0, "()Ljava/lang/Object;", "clone", "CGLIB$clone$4");
        CGLIB$say$0$Method = ReflectUtils.findMethods(new String[]{"say", "()V"}, (var1 = Class.forName("seven.com.seven.aop.Hello")).getDeclaredMethods())[0];
        CGLIB$say$0$Proxy = MethodProxy.create(var1, var0, "()V", "say", "CGLIB$say$0");
    }

    final void CGLIB$say$0() {
        super.say();
    }

        /**
         * 执行方法时判断是否有callback(MethodInterceptor 类型的对象),有的话是执行其intercept方法,并且传入上面生成的MethodProxy对象
         */
    public final void say() {
        MethodInterceptor var10000 = this.CGLIB$CALLBACK_0;
        if (this.CGLIB$CALLBACK_0 == null) {
            CGLIB$BIND_CALLBACKS(this);
            var10000 = this.CGLIB$CALLBACK_0;
        }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        return null;
    }

    public Hello$$EnhancerByCGLIB$$f0ec8381() {
        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) {
        Hello$$EnhancerByCGLIB$$f0ec8381 var1 = (Hello$$EnhancerByCGLIB$$f0ec8381)var0;
        if (!var1.CGLIB$BOUND) {
            var1.CGLIB$BOUND = true;
            Object var10000 = CGLIB$THREAD_CALLBACKS.get();
            if (var10000 == null) {
                var10000 = CGLIB$STATIC_CALLBACKS;
                if (CGLIB$STATIC_CALLBACKS == null) {
                    return;
                }
            }

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

    }

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

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

    public Object newInstance(Class[] var1, Object[] var2, Callback[] var3) {
        CGLIB$SET_THREAD_CALLBACKS(var3);
        Hello$$EnhancerByCGLIB$$f0ec8381 var10000 = new Hello$$EnhancerByCGLIB$$f0ec8381;
        switch(var1.length) {
        case 0:
            var10000.();
            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$STATICHOOK1();
    }
}

解析
  1. 动态代理类是在静态构造函数中把每一个父类的方法分别对应创建了一个MethodProxy对象,也就是方法代理对象
  2. 执行对应方法时,比如Hello类中的say方法,会先判断是否存在CallBack,也就是创建代理类时enhancer.setCallback(this);这句代码指定的callback,因为callback本身是MethodInterceptor类型,如果存在则执行其intercept方法,这也就解释了为什么最终会执行到我们定义的DynamicCGLibProxy的中,因为它就是实现了MethodInterceptor接口的callback,执行到这里我们自然可以在方法前后做一些拦截,增强原始对象的功能,达到代理的目的

CGLIB的动态代理

MethodInterceptor

public interface MethodInterceptor
extends Callback
{  
  /**
     * 被代理的对象的方法最终会执行到这里,在这里可以在方法执行前后做一些拦截,
     * 增加一些逻辑,甚至可以不执行原来的方法,执行方法通过MethodProxy 
     * 这个方法代理对象来执行
     * @param obj  最终生成的代理对象,也就是上面源码中看到的
     * @param method 被拦截的方法
     * @param args  被拦截的方法的参数集合
     * @param proxy 方法的代理对象,如上面解释CGLIB会把生成的代理类父类【本例中为Hello和Object】中的每个方法都单独生成一个MethodProxy,用来最终执行父类的方法
     */ 
    public Object intercept(Object obj, java.lang.reflect.Method method, Object[] args,
                               MethodProxy proxy) throws Throwable;

}

MethodProxy

package net.sf.cglib.proxy;
public class MethodProxy {

    /**
     * 通过此方法执行原对象(被代理的对象)的方法,可以看到是执行fci.f2.invoke,在文章开篇就讲到生成的代理类不止一个,这里其实最终是实行了继承了FastClass的一个代理类Hello$$FastClassByCGLIB$$c45ea757,最终执行了被代理对象的方法
     * @param obj 生成的代理的对象
     * @param args 方法的参数
     */
    public Object invokeSuper(Object obj, Object[] args) throws Throwable {
        try {
            init();
            FastClassInfo fci = fastClassInfo;
            return fci.f2.invoke(fci.i2, obj, args);
        } catch (InvocationTargetException e) {
            throw e.getTargetException();
        }
    }
}


下面是和代理类一起生成的其中一个继承自FastClass的类文件,当执行MethodProxy的invokeSuper方法时其实就是执行这个对象的invoke方法

package seven.com.seven.aop;

import java.lang.reflect.InvocationTargetException;
import net.sf.cglib.core.Signature;
import net.sf.cglib.reflect.FastClass;

public class Hello$$FastClassByCGLIB$$c45ea757 extends FastClass {
    public Hello$$FastClassByCGLIB$$c45ea757(Class var1) {
        super(var1);
    }

    public int getIndex(Signature var1) {
        String var10000 = var1.toString();
        switch(var10000.hashCode()) {
        case -909388886:
            if (var10000.equals("say()V")) {
                return 0;
            }
            break;
        case 1826985398:
            if (var10000.equals("equals(Ljava/lang/Object;)Z")) {
                return 1;
            }
            break;
        case 1913648695:
            if (var10000.equals("toString()Ljava/lang/String;")) {
                return 2;
            }
            break;
        case 1984935277:
            if (var10000.equals("hashCode()I")) {
                return 3;
            }
        }

        return -1;
    }

    public int getIndex(String var1, Class[] var2) {
        switch(var1.hashCode()) {
        case -1776922004:
            if (var1.equals("toString")) {
                switch(var2.length) {
                case 0:
                    return 2;
                }
            }
            break;
        case -1295482945:
            if (var1.equals("equals")) {
                switch(var2.length) {
                case 1:
                    if (var2[0].getName().equals("java.lang.Object")) {
                        return 1;
                    }
                }
            }
            break;
        case 113643:
            if (var1.equals("say")) {
                switch(var2.length) {
                case 0:
                    return 0;
                }
            }
            break;
        case 147696667:
            if (var1.equals("hashCode")) {
                switch(var2.length) {
                case 0:
                    return 3;
                }
            }
        }

        return -1;
    }

    public int getIndex(Class[] var1) {
        switch(var1.length) {
        case 0:
            return 0;
        default:
            return -1;
        }
    }

    /**
     * 上面MethodProxy的invoke方法最终会执行到这里,也就是执行被代理对象的具体方法上
     */ 
    public Object invoke(int var1, Object var2, Object[] var3) throws InvocationTargetException {
        Hello var10000 = (Hello)var2;
        int var10001 = var1;

        try {
            switch(var10001) {
            case 0:
                var10000.say();
                return null;
            case 1:
                return new Boolean(var10000.equals(var3[0]));
            case 2:
                return var10000.toString();
            case 3:
                return new Integer(var10000.hashCode());
            }
        } catch (Throwable var4) {
            throw new InvocationTargetException(var4);
        }

        throw new IllegalArgumentException("Cannot find matching method/constructor");
    }

    public Object newInstance(int var1, Object[] var2) throws InvocationTargetException {
        Hello var10000 = new Hello;
        Hello var10001 = var10000;
        int var10002 = var1;

        try {
            switch(var10002) {
            case 0:
                var10001.();
                return var10000;
            }
        } catch (Throwable var3) {
            throw new InvocationTargetException(var3);
        }

        throw new IllegalArgumentException("Cannot find matching method/constructor");
    }

    public int getMaxIndex() {
        return 3;
    }
}


JDK动态代理和CGLIB字节码生成的区别

  1. JDK动态代理只能对实现了接口的类生成代理,而不能针对类。
  2. CGLIB是针对类实现代理,主要是对指定的类生成一个子类,覆盖其中的方法,
    并覆盖其中方法实现增强,但是因为采用的是继承,所以该类或方法最好不要声明成final,
    对于final类或方法,是无法继承的

微信公众号:宋坤明
下面的是我的公众号二维码图片,欢迎关注。


图注:宋坤明公众号

你可能感兴趣的:(CGLIB动态代理)