CGLib动态代理

本文详细介绍了CGLib动态代理的原理和使用,包括如何创建代理对象、设置拦截器和回调方法,以及在懒加载和接口生成等方面的应用。通过示例代码展示了CGLib如何实现代理类的生成和方法拦截,强调了其无需接口、方法级别拦截和不使用反射执行等特点。
摘要由CSDN通过智能技术生成

CGLib动态代理

1.概述

  1. CGLib动态代理不要求委托方法需要实现接口。
  2. CGLib动态代理能够实现基于方法级别的拦截处理。
  3. CGLib动态代理执行方法,不是使用反射执行Method.invoke()。
  4. CGLib不能对声明为final的方法进行代理。

2.使用

1.Callback
public class TargetObject {
    public String method1(String paramName) {
        return paramName;
    }

    public int method2(int count) {
        return count;
    }

    public int method3(int count) {
        return count;
    }

    @Override
    public String toString() {
        return "TargetObject []"+ getClass();
    }
}
public class TargetInterceptor implements MethodInterceptor {
    /**
     * 重写方法拦截在方法前和方法后加入业务
     * Object obj为目标对象
     * Method method为目标方法
     * Object[] params 为参数,
     * MethodProxy proxy CGlib方法代理对象
     */
    public Object intercept(Object obj, Method method, Object[] params,
                            MethodProxy proxy) throws Throwable {
        System.out.println("调用前");
        Object result = proxy.invokeSuper(obj, params);
        System.out.println(" 调用后"+result);
        return result;
    }
}
public class TargetResultFixed implements FixedValue {

    /**
     * 该类实现FixedValue接口,同时锁定回调值为999
     * (整型,CallbackFilter中定义的使用FixedValue型回调的方法为getConcreteMethodFixedValue,该方法返回值为整型)。
     */

    public Object loadObject() throws Exception {
        System.out.println("锁定结果");
        Object obj = 999;
        return obj;
    }

}
public class TargetMethodCallbackFilter implements CallbackFilter {

    /**
     * 过滤方法
     * 返回的值为数字,代表了Callback数组中的索引位置,要到用的Callback
     */
    public int accept(Method method) {
        if(method.getName().equals("method1")){
            System.out.println("filter method1 ==0");
            return 0;
        }
        if(method.getName().equals("method2")){
            System.out.println("filter method2 ==1");
            return 1;
        }
        if(method.getName().equals("method3")){
            System.out.println("filter method3 ==2");
            return 2;
        }
        return 0;
    }

}
public class TestCglib {
    public static void main(String args[]) throws Exception{
        Enhancer enhancer =new Enhancer();
        enhancer.setSuperclass(TargetObject.class);
        CallbackFilter callbackFilter = new TargetMethodCallbackFilter();

        /**
         * (1)callback1:方法拦截器
         (2)NoOp.INSTANCE:这个NoOp表示no operator,即什么操作也不做,代理类直接调用被代理的方法不进行拦截。
         (3)FixedValue:表示锁定方法返回值,无论被代理类的方法返回什么值,回调方法都返回固定值。
         */
        Callback noopCb= NoOp.INSTANCE;
        Callback callback1=new TargetInterceptor();
        Callback fixedValue=new TargetResultFixed();
        Callback[] cbarray=new Callback[]{callback1,noopCb,fixedValue};
        //enhancer.setCallback(new TargetInterceptor());
        enhancer.setCallbacks(cbarray);
        enhancer.setCallbackFilter(callbackFilter);
        TargetObject targetObject2=(TargetObject)enhancer.create();
        System.out.println(targetObject2);
        System.out.println(targetObject2.method1("mmm1"));
        System.out.println(targetObject2.method2(100));
        System.out.println(targetObject2.method3(100));
        System.out.println(targetObject2.method3(200));
        //下述方法将生成的代理类字节码输出到class文件中,然后反编译查看。
        byte[] b = new DefaultGeneratorStrategy().generate(enhancer);
        File file = new File("MyProxyClass.class");
        FileOutputStream fos = new FileOutputStream(file);
        fos.write(b);
        fos.flush();
        fos.close();
    }
}

结果:

在这里插入图片描述

对字节码进行反编译分析:

//该类继承自目标类(被代理类)
public class TargetObject$$EnhancerByCGLIB$$413697a3 extends TargetObject implements Factory {
    private boolean CGLIB$BOUND;
    private static final ThreadLocal CGLIB$THREAD_CALLBACKS;
    private static final Callback[] CGLIB$STATIC_CALLBACKS;
    private MethodInterceptor CGLIB$CALLBACK_0;
    private NoOp CGLIB$CALLBACK_1;
    private FixedValue CGLIB$CALLBACK_2;
    private static final Method CGLIB$toString$0$Method;
    private static final MethodProxy CGLIB$toString$0$Proxy;
    private static final Object[] CGLIB$emptyArgs;
    private static final Method CGLIB$method1$2$Method;
    private static final MethodProxy CGLIB$method1$2$Proxy;
    private static final Method CGLIB$finalize$4$Method;
    private static final MethodProxy CGLIB$finalize$4$Proxy;
    private static final Method CGLIB$equals$5$Method;
    private static final MethodProxy CGLIB$equals$5$Proxy;
    private static final Method CGLIB$hashCode$6$Method;
    private static final MethodProxy CGLIB$hashCode$6$Proxy;
    private static final Method CGLIB$clone$7$Method;
    private static final MethodProxy CGLIB$clone$7$Proxy;

    //在该类加载时,调用,为上面的静态属性赋值。
    static void CGLIB$STATICHOOK2() {
        CGLIB$THREAD_CALLBACKS = new ThreadLocal();
        CGLIB$emptyArgs = new Object[0];
        Class var0 = Class.forName("Designpattern.CGlibProxy.scholl.TargetObject$$EnhancerByCGLIB$$413697a3");
        Class var1;
        Method[] var10000 = ReflectUtils.findMethods(new String[]{"toString", "()Ljava/lang/String;", "method1", "(Ljava/lang/String;)Ljava/lang/String;"}, (var1 = Class.forName("Designpattern.CGlibProxy.scholl.TargetObject")).getDeclaredMethods());
        CGLIB$toString$0$Method = var10000[0];
        CGLIB$toString$0$Proxy = MethodProxy.create(var1, var0, "()Ljava/lang/String;", "toString", "CGLIB$toString$0");
        CGLIB$method1$2$Method = var10000[1];
        CGLIB$method1$2$Proxy = MethodProxy.create(var1, var0, "(Ljava/lang/String;)Ljava/lang/String;", "method1", "CGLIB$method1$2");
        var10000 = ReflectUtils.findMethods(new String[]{"finalize", "()V", "equals", "(Ljava/lang/Object;)Z", "hashCode", "()I", "clone", "()Ljava/lang/Object;"}, (var1 = Class.forName("java.lang.Object")).getDeclaredMethods());
        CGLIB$finalize$4$Method = var10000[0];
        CGLIB$finalize$4$Proxy = MethodProxy.create(var1, var0, "()V", "finalize", "CGLIB$finalize$4");
        CGLIB$equals$5$Method = var10000[1];
        CGLIB$equals$5$Proxy = MethodProxy.create(var1, var0, "(Ljava/lang/Object;)Z", "equals", "CGLIB$equals$5");
        CGLIB$hashCode$6$Method = var10000[2];
        CGLIB$hashCode$6$Proxy = MethodProxy.create(var1, var0, "()I", "hashCode", "CGLIB$hashCode$6");
        CGLIB$clone$7$Method = var10000[3];
        CGLIB$clone$7$Proxy = MethodProxy.create(var1, var0, "()Ljava/lang/Object;", "clone", "CGLIB$clone$7");
    }
	//带有CGLIB$xxx的方法,最终会调用父类方法。
    final String CGLIB$toString$0() {
        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$0$Method, CGLIB$emptyArgs, CGLIB$toString$0$Proxy) : super.toString();
    }

    final String CGLIB$method1$2(String var1) {
        return super.method1(var1);
    }
	//目标类的method1方法。
    public final String method1(String var1) {
        MethodInterceptor var10000 = this.CGLIB$CALLBACK_0;
        if (var10000 == null) {
            CGLIB$BIND_CALLBACKS(this);
            var10000 = this.CGLIB$CALLBACK_0;
        }
		//调用MethodInterceptor.intercept()
        return var10000 != null ? (String)var10000.intercept(this, CGLIB$method1$2$Method, new Object[]{var1}, CGLIB$method1$2$Proxy) : super.method1(var1);
    }

    final void CGLIB$finalize$4() throws Throwable {
        super.finalize();
    }

    protected final void finalize() throws Throwable {
        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$finalize$4$Method, CGLIB$emptyArgs, CGLIB$finalize$4$Proxy);
        } else {
            super.finalize();
        }
    }

    final boolean CGLIB$equals$5(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$5$Method, new Object[]{var1}, CGLIB$equals$5$Proxy);
            return var2 == null ? false : (Boolean)var2;
        } else {
            return super.equals(var1);
        }
    }

    final int CGLIB$hashCode$6() {
        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$6$Method, CGLIB$emptyArgs, CGLIB$hashCode$6$Proxy);
            return var1 == null ? 0 : ((Number)var1).intValue();
        } else {
            return super.hashCode();
        }
    }

    final Object CGLIB$clone$7() 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$7$Method, CGLIB$emptyArgs, CGLIB$clone$7$Proxy) : super.clone();
    }

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

        return null;
    }
	//method3
    public final int method3(int var1) {
        FixedValue var10000 = this.CGLIB$CALLBACK_2;
        if (var10000 == null) {
            CGLIB$BIND_CALLBACKS(this);
            var10000 = this.CGLIB$CALLBACK_2;
        }
		//直接调用FixedValue.loadObject()
        Object var2 = var10000.loadObject();
        return var2 == null ? 0 : ((Number)var2).intValue();
    }
	//代理类的构造方法
    public TargetObject$$EnhancerByCGLIB$$413697a3() {
        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) {
        TargetObject$$EnhancerByCGLIB$$413697a3 var1 = (TargetObject$$EnhancerByCGLIB$$413697a3)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;
                }
            }

            Callback[] var10001 = (Callback[])var10000;
            var1.CGLIB$CALLBACK_2 = (FixedValue)((Callback[])var10000)[2];
            var1.CGLIB$CALLBACK_1 = (NoOp)var10001[1];
            var1.CGLIB$CALLBACK_0 = (MethodInterceptor)var10001[0];
        }

    }
	//返回一个新的该代理类
    public Object newInstance(Callback[] var1) {
        CGLIB$SET_THREAD_CALLBACKS(var1);
        TargetObject$$EnhancerByCGLIB$$413697a3 var10000 = new TargetObject$$EnhancerByCGLIB$$413697a3();
        CGLIB$SET_THREAD_CALLBACKS((Callback[])null);
        return var10000;
    }

    public Object newInstance(Callback var1) {
        throw new IllegalStateException("More than one callback object required");
    }

    public Object newInstance(Class[] var1, Object[] var2, Callback[] var3) {
        CGLIB$SET_THREAD_CALLBACKS(var3);
        TargetObject$$EnhancerByCGLIB$$413697a3 var10000 = new TargetObject$$EnhancerByCGLIB$$413697a3;
        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);
        Object var10000;
        switch(var1) {
        case 0:
            var10000 = this.CGLIB$CALLBACK_0;
            break;
        case 1:
            var10000 = this.CGLIB$CALLBACK_1;
            break;
        case 2:
            var10000 = this.CGLIB$CALLBACK_2;
            break;
        default:
            var10000 = null;
        }

        return (Callback)var10000;
    }

    public void setCallback(int var1, Callback var2) {
        switch(var1) {
        case 0:
            this.CGLIB$CALLBACK_0 = (MethodInterceptor)var2;
            break;
        case 1:
            this.CGLIB$CALLBACK_1 = (NoOp)var2;
            break;
        case 2:
            this.CGLIB$CALLBACK_2 = (FixedValue)var2;
        }

    }

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

    public void setCallbacks(Callback[] var1) {
        this.CGLIB$CALLBACK_0 = (MethodInterceptor)var1[0];
        this.CGLIB$CALLBACK_1 = (NoOp)var1[1];
        this.CGLIB$CALLBACK_2 = (FixedValue)var1[2];
    }
	//调用最开始的那个静态方法。
    static {
        CGLIB$STATICHOOK2();
    }
}
//可以看到没有method2方法,因为method2方法使用NoOp.INSTANCE拦截,因此可以直接调用代理类父类的method2方法.
2.懒加载
public class TargetObject {
    public String method1(String paramName) {
        return paramName;
    }

    public int method2(int count) {
        return count;
    }

    public int method3(int count) {
        return count;
    }

    @Override
    public String toString() {
        return "TargetObject []"+ getClass();
    }
public class PropertyBean {
    private String key;
    private Object value;
    public String getKey() {
        return key;
    }
    public void setKey(String key) {
        this.key = key;
    }
    public Object getValue() {
        return value;
    }
    public void setValue(Object value) {
        this.value = value;
    }
    @Override
    public String toString() {
        return "PropertyBean [key=" + key + ", value=" + value + "]" +getClass();
    }

}
public class ConcreteClassLazyLoader implements LazyLoader {
    /**
     * 对需要延迟加载的对象添加代理,在获取该对象属性时先通过代理类回调方法进行对象初始化。
     * 在不需要加载该对象时,只要不去获取该对象内属性,该对象就不会被初始化了(在CGLib的实现中只要去访问该对象内属性的getter方法,
     * 就会自动触发代理类回调)。
     */

    public Object loadObject() throws Exception {
        System.out.println("before lazyLoader...");
        PropertyBean propertyBean = new PropertyBean();
        propertyBean.setKey("zghw");
        propertyBean.setValue(new TargetObject());
        System.out.println("after lazyLoader...");
        return propertyBean;
    }

}
public class ConcreteClassDispatcher implements Dispatcher{


    public Object loadObject() throws Exception {
        System.out.println("before Dispatcher...");
        PropertyBean propertyBean = new PropertyBean();
        propertyBean.setKey("xxx");
        propertyBean.setValue(new TargetObject());
        System.out.println("after Dispatcher...");
        return propertyBean;
    }

}
public class LazyBean {
    private String name;
    private int age;
    private PropertyBean propertyBean;
    private PropertyBean propertyBeanDispatcher;

    public LazyBean(String name, int age) {
        System.out.println("lazy bean init");
        this.name = name;
        this.age = age;
        this.propertyBean = createPropertyBean();
        this.propertyBeanDispatcher = createPropertyBeanDispatcher();
    }



    /**
     * 只第一次懒加载
     * @return
     */
    private PropertyBean createPropertyBean() {
        /**
         * 使用cglib进行懒加载 对需要延迟加载的对象添加代理,在获取该对象属性时先通过代理类回调方法进行对象初始化。
         * 在不需要加载该对象时,只要不去获取该对象内属性,该对象就不会被初始化了(在CGLib的实现中只要去访问该对象内属性的getter方法,
         * 就会自动触发代理类回调)。
         */
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(PropertyBean.class);
        PropertyBean pb = (PropertyBean) enhancer.create(PropertyBean.class,
                new ConcreteClassLazyLoader());
        return pb;
    }
    /**
     * 每次都懒加载
     * @return
     */
    private PropertyBean createPropertyBeanDispatcher() {
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(PropertyBean.class);
        PropertyBean pb = (PropertyBean) enhancer.create(PropertyBean.class,
                new ConcreteClassDispatcher());
        return pb;
    }
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public PropertyBean getPropertyBean() {
        return propertyBean;
    }

    public void setPropertyBean(PropertyBean propertyBean) {
        this.propertyBean = propertyBean;
    }

    public PropertyBean getPropertyBeanDispatcher() {
        return propertyBeanDispatcher;
    }

    public void setPropertyBeanDispatcher(PropertyBean propertyBeanDispatcher) {
        this.propertyBeanDispatcher = propertyBeanDispatcher;
    }

    @Override
    public String toString() {
        return "LazyBean [name=" + name + ", age=" + age + ", propertyBean="
                + propertyBean + "]";
    }
}

测试:

public class Main {
    public static void main(String[] args) throws Exception{
        LazyBean lazyBean  = new LazyBean("涨",20);
        System.out.println("lazyBean---------实例化完成");
        lazyBean.getPropertyBean().getValue();
        lazyBean.getPropertyBean().getValue();
        System.out.println("----------------------------");
        lazyBean.getPropertyBeanDispatcher().getValue();
        lazyBean.getPropertyBeanDispatcher().getValue();

    }
}

结果:

在这里插入图片描述

3.根据目标类,新建接口
public class TargetObject {
    public String method1(String paramName) {
        return paramName;
    }

    public int method2(int count) {
        return count;
    }

    public int method3(int count) {
        return count;
    }

    @Override
    public String toString() {
        return "TargetObject []"+ getClass();
    }
}
public class TestInterfaceMaker {

    public static void main(String[] args) throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
        InterfaceMaker interfaceMaker =new InterfaceMaker();
        //抽取某个类的方法生成接口方法
        interfaceMaker.add(TargetObject.class);
        Class<?> targetInterface=interfaceMaker.create();
        for(Method method : targetInterface.getMethods()){
            System.out.println(method.getName());
        }
        //接口代理并设置代理接口方法拦截
        Object object = Enhancer.create(Object.class, new Class[]{targetInterface}, new MethodInterceptor(){

            public Object intercept(Object obj, Method method, Object[] args,
                                    MethodProxy methodProxy) throws Throwable {
                if(method.getName().equals("method1")){
                    System.out.println("filter method1 ");
                    return "mmmmmmmmm";
                }
                if(method.getName().equals("method2")){
                    System.out.println("filter method2 ");
                    return 1111111;
                }
                if(method.getName().equals("method3")){
                    System.out.println("filter method3 ");
                    return 3333;
                }
                return "default";
            }});
        Method targetMethod1=object.getClass().getMethod("method3",new Class[]{int.class});
        int i=(Integer) targetMethod1.invoke(object, new Object[]{33});
        Method targetMethod=object.getClass().getMethod("method1",new Class[]{String.class});
        System.out.println(targetMethod.invoke(object, new Object[]{"sdfs"}));
    }
}

结果:
在这里插入图片描述

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值