zoukankan      html  css  js  c++  java
  • CGLIB介绍

    一、什么是CGLIB?

    CGLIB是一个功能强大,高性能的代码生成包。它为没有实现接口的类提供代理,为JDK的动态代理提供了很好的补充。通常可以使用Java的动态代理创建代理,但当要代理的类没有实现接口或者为了更好的性能,CGLIB是一个好的选择。

    二、CGLIB原理

    CGLIB原理:动态生成一个要代理类的子类,子类重写要代理的类的所有不是final的方法。在子类中采用方法拦截的技术拦截所有父类方法的调用,顺势织入横切逻辑。它比使用java反射的JDK动态代理要快。

    CGLIB底层:使用字节码处理框架ASM,来转换字节码并生成新的类。不鼓励直接使用ASM,因为它要求你必须对JVM内部结构包括class文件的格式和指令集都很熟悉。

    CGLIB缺点:对于final方法,无法进行代理。

    三、CGLIB的应用

    广泛的被许多AOP的框架使用,例如Spring AOP和dynaop。Hibernate使用CGLIB来代理单端single-ended(多对一和一对一)关联。

    四、CGLIB的API

    1、Jar包

    cglib-nodep-2.2.jar:使用nodep包不需要关联asm的jar包,jar包内部包含asm的类.

    cglib-2.2.jar:使用此jar包需要关联asm的jar包,否则运行时报错.

    2、CGLIB类库:

    由于基本代码很少,学起来有一定的困难,主要是缺少文档和示例,这也是CGLIB的一个不足之处

    本系列使用的CGLIB版本是2.2

    net.sf.cglib.core:底层字节码处理类,他们大部分与ASM有关系。

    net.sf.cglib.transform:编译期或运行期类和类文件的转换

    net.sf.cglib.proxy:实现创建代理和方法拦截器的类

    net.sf.cglib.reflect:实现快速反射和C#风格代理的类

    net.sf.cglib.util:集合排序等工具类

    net.sf.cglib.beans:JavaBean相关的工具类

    本篇介绍通过MethodInterceptor和Enhancer实现一个动态代理。

    一、首先说一下JDK中的动态代理

    JDK中的动态代理是通过反射类Proxy以及InvocationHandler回调接口实现的,

    但是,JDK中所要进行动态代理的类必须要实现一个接口,也就是说只能对该类所实现接口中定义的方法进行代理,这在实际编程中具有一定的局限性,而且使用反射的效率也并不是很高。

    二、使用CGLib实现

    使用CGLib实现动态代理,完全不受代理类必须实现接口的限制,而且CGLib底层采用ASM字节码生成框架,使用字节码技术生成代理类,比使用Java反射效率要高。唯一需要注意的是,CGLib不能对声明为final的方法进行代理,因为CGLib原理是动态生成被代理类的子类。

    下面,将通过一个实例介绍使用CGLib实现动态代理。

    1、被代理类

    首先,定义一个类,该类没有实现任何接口

    1. <span style="font-size:14px;">package com.zghw.cglib;  
    2.   
    3. /** 
    4.  * 没有实现接口,需要CGlib动态代理的目标类 
    5.  *  
    6.  * @author zghw 
    7.  * 
    8.  */  
    9. public class TargetObject {  
    10.     public String method1(String paramName) {  
    11.         return paramName;  
    12.     }  
    13.   
    14.     public int method2(int count) {  
    15.         return count;  
    16.     }  
    17.   
    18.     public int method3(int count) {  
    19.         return count;  
    20.     }  
    21.   
    22.     @Override  
    23.     public String toString() {  
    24.         return "TargetObject []"+ getClass();  
    25.     }  
    26. }</span>  

     

    2、拦截器

    定义一个拦截器。在调用目标方法时,CGLib会回调MethodInterceptor接口方法拦截,来实现你自己的代理逻辑,类似于JDK中的InvocationHandler接口。

    1. <span style="font-size:14px;">package com.zghw.cglib;  
    2.   
    3. import java.lang.reflect.Method;  
    4.   
    5. import net.sf.cglib.proxy.MethodInterceptor;  
    6. import net.sf.cglib.proxy.MethodProxy;  
    7. /** 
    8.  * 目标对象拦截器,实现MethodInterceptor 
    9.  * @author zghw 
    10.  * 
    11.  */  
    12. public class TargetInterceptor implements MethodInterceptor{  
    13.   
    14.     /** 
    15.      * 重写方法拦截在方法前和方法后加入业务 
    16.      * Object obj为目标对象 
    17.      * Method method为目标方法 
    18.      * Object[] params 为参数, 
    19.      * MethodProxy proxy CGlib方法代理对象 
    20.      */  
    21.     @Override  
    22.     public Object intercept(Object obj, Method method, Object[] params,  
    23.             MethodProxy proxy) throws Throwable {  
    24.         System.out.println("调用前");  
    25.         Object result = proxy.invokeSuper(obj, params);  
    26.         System.out.println(" 调用后"+result);  
    27.         return result;  
    28.     }  
    29.   
    30.   
    31. }  
    32. </span>  


    参数:Object为由CGLib动态生成的代理类实例,Method为上文中实体类所调用的被代理的方法引用,Object[]为参数值列表,MethodProxy为生成的代理类对方法的代理引用。

    返回:从代理实例的方法调用返回的值。

    其中,proxy.invokeSuper(obj,arg):

    调用代理类实例上的proxy方法的父类方法(即实体类TargetObject中对应的方法)

    在这个示例中,只在调用被代理类方法前后各打印了一句话,当然实际编程中可以是其它复杂逻辑。

    3、生成动态代理类

    1. <span style="font-size:14px;">package com.zghw.cglib;  
    2.   
    3. import net.sf.cglib.proxy.Callback;  
    4. import net.sf.cglib.proxy.CallbackFilter;  
    5. import net.sf.cglib.proxy.Enhancer;  
    6. import net.sf.cglib.proxy.NoOp;  
    7.   
    8. public class TestCglib {  
    9.     public static void main(String args[]) {  
    10.         Enhancer enhancer =new Enhancer();  
    11.         enhancer.setSuperclass(TargetObject.class);  
    12.         enhancer.setCallback(new TargetInterceptor());  
    13.         TargetObject targetObject2=(TargetObject)enhancer.create();  
    14.         System.out.println(targetObject2);  
    15.         System.out.println(targetObject2.method1("mmm1"));  
    16.         System.out.println(targetObject2.method2(100));  
    17.         System.out.println(targetObject2.method3(200));  
    18.     }  
    19. }  
    20. </span>  

    这里Enhancer类是CGLib中的一个字节码增强器,它可以方便的对你想要处理的类进行扩展,以后会经常看到它。

    首先将被代理类TargetObject设置成父类,然后设置拦截器TargetInterceptor,最后执行enhancer.create()动态生成一个代理类,并从Object强制转型成父类型TargetObject。

    最后,在代理类上调用方法.

    4、回调过滤器CallbackFilter

    一、作用

    在CGLib回调时可以设置对不同方法执行不同的回调逻辑,或者根本不执行回调。

    在JDK动态代理中并没有类似的功能,对InvocationHandler接口方法的调用对代理类内的所以方法都有效。


    定义实现过滤器CallbackFilter接口的类:

    1. <span style="font-size:14px;">package com.zghw.cglib;  
    2.   
    3. import java.lang.reflect.Method;  
    4.   
    5. import net.sf.cglib.proxy.CallbackFilter;  
    6. /** 
    7.  * 回调方法过滤 
    8.  * @author zghw 
    9.  * 
    10.  */  
    11. public class TargetMethodCallbackFilter implements CallbackFilter {  
    12.   
    13.     /** 
    14.      * 过滤方法 
    15.      * 返回的值为数字,代表了Callback数组中的索引位置,要到用的Callback 
    16.      */  
    17.     @Override  
    18.     public int accept(Method method) {  
    19.         if(method.getName().equals("method1")){  
    20.             System.out.println("filter method1 ==0");  
    21.             return 0;  
    22.         }  
    23.         if(method.getName().equals("method2")){  
    24.             System.out.println("filter method2 ==1");  
    25.             return 1;  
    26.         }  
    27.         if(method.getName().equals("method3")){  
    28.             System.out.println("filter method3 ==2");  
    29.             return 2;  
    30.         }  
    31.         return 0;  
    32.     }  
    33.   
    34. }  
    35. </span>  


    其中return值为被代理类的各个方法在回调数组Callback[]中的位置索引(见下文)。

    1. <span style="font-size:14px;">package com.zghw.cglib;  
    2.   
    3. import net.sf.cglib.proxy.Callback;  
    4. import net.sf.cglib.proxy.CallbackFilter;  
    5. import net.sf.cglib.proxy.Enhancer;  
    6. import net.sf.cglib.proxy.NoOp;  
    7.   
    8. public class TestCglib {  
    9.     public static void main(String args[]) {  
    10.         Enhancer enhancer =new Enhancer();  
    11.         enhancer.setSuperclass(TargetObject.class);  
    12.         CallbackFilter callbackFilter = new TargetMethodCallbackFilter();  
    13.           
    14.         /** 
    15.          * (1)callback1:方法拦截器 
    16.            (2)NoOp.INSTANCE:这个NoOp表示no operator,即什么操作也不做,代理类直接调用被代理的方法不进行拦截。 
    17.            (3)FixedValue:表示锁定方法返回值,无论被代理类的方法返回什么值,回调方法都返回固定值。 
    18.          */  
    19.         Callback noopCb=NoOp.INSTANCE;  
    20.         Callback callback1=new TargetInterceptor();  
    21.         Callback fixedValue=new TargetResultFixed();  
    22.         Callback[] cbarray=new Callback[]{callback1,noopCb,fixedValue};  
    23.         //enhancer.setCallback(new TargetInterceptor());  
    24.         enhancer.setCallbacks(cbarray);  
    25.         enhancer.setCallbackFilter(callbackFilter);  
    26.         TargetObject targetObject2=(TargetObject)enhancer.create();  
    27.         System.out.println(targetObject2);  
    28.         System.out.println(targetObject2.method1("mmm1"));  
    29.         System.out.println(targetObject2.method2(100));  
    30.         System.out.println(targetObject2.method3(100));  
    31.         System.out.println(targetObject2.method3(200));  
    32.     }  
    33. }  
    34. </span>  


    1. <span style="font-size:14px;">package com.zghw.cglib;  
    2.   
    3. import net.sf.cglib.proxy.FixedValue;  
    4. /**  
    5.  * 表示锁定方法返回值,无论被代理类的方法返回什么值,回调方法都返回固定值。  
    6.  * @author zghw  
    7.  *  
    8.  */  
    9. public class TargetResultFixed implements FixedValue{  
    10.   
    11.     /**  
    12.      * 该类实现FixedValue接口,同时锁定回调值为999  
    13.      * (整型,CallbackFilter中定义的使用FixedValue型回调的方法为getConcreteMethodFixedValue,该方法返回值为整型)。  
    14.      */  
    15.     @Override  
    16.     public Object loadObject() throws Exception {  
    17.         System.out.println("锁定结果");  
    18.         Object obj = 999;  
    19.         return obj;  
    20.     }  
    21.   
    22. }  
    23. </span>  


    5.延迟加载对象

    一、作用:
    说到延迟加载,应该经常接触到,尤其是使用Hibernate的时候,本篇将通过一个实例分析延迟加载的实现方式。
    LazyLoader接口继承了Callback,因此也算是CGLib中的一种Callback类型。

    另一种延迟加载接口Dispatcher。

    Dispatcher接口同样继承于Callback,也是一种回调类型。

    但是Dispatcher和LazyLoader的区别在于:LazyLoader只在第一次访问延迟加载属性时触发代理类回调方法,而Dispatcher在每次访问延迟加载属性时都会触发代理类回调方法。


    二、示例:
    首先定义一个实体类LoaderBean,该Bean内有一个需要延迟加载的属性PropertyBean。


    1. <span style="font-size:14px;">package com.zghw.cglib;  
    2.   
    3. import net.sf.cglib.proxy.Enhancer;  
    4.   
    5. public class LazyBean {  
    6.     private String name;  
    7.     private int age;  
    8.     private PropertyBean propertyBean;  
    9.     private PropertyBean propertyBeanDispatcher;  
    10.   
    11.     public LazyBean(String name, int age) {  
    12.         System.out.println("lazy bean init");  
    13.         this.name = name;  
    14.         this.age = age;  
    15.         this.propertyBean = createPropertyBean();  
    16.         this.propertyBeanDispatcher = createPropertyBeanDispatcher();  
    17.     }  
    18.   
    19.       
    20.   
    21.     /** 
    22.      * 只第一次懒加载 
    23.      * @return 
    24.      */  
    25.     private PropertyBean createPropertyBean() {  
    26.         /** 
    27.          * 使用cglib进行懒加载 对需要延迟加载的对象添加代理,在获取该对象属性时先通过代理类回调方法进行对象初始化。 
    28.          * 在不需要加载该对象时,只要不去获取该对象内属性,该对象就不会被初始化了(在CGLib的实现中只要去访问该对象内属性的getter方法, 
    29.          * 就会自动触发代理类回调)。 
    30.          */  
    31.         Enhancer enhancer = new Enhancer();  
    32.         enhancer.setSuperclass(PropertyBean.class);  
    33.         PropertyBean pb = (PropertyBean) enhancer.create(PropertyBean.class,  
    34.                 new ConcreteClassLazyLoader());  
    35.         return pb;  
    36.     }  
    37.     /** 
    38.      * 每次都懒加载 
    39.      * @return 
    40.      */  
    41.     private PropertyBean createPropertyBeanDispatcher() {  
    42.         Enhancer enhancer = new Enhancer();  
    43.         enhancer.setSuperclass(PropertyBean.class);  
    44.         PropertyBean pb = (PropertyBean) enhancer.create(PropertyBean.class,  
    45.                 new ConcreteClassDispatcher());  
    46.         return pb;  
    47.     }  
    48.     public String getName() {  
    49.         return name;  
    50.     }  
    51.   
    52.     public void setName(String name) {  
    53.         this.name = name;  
    54.     }  
    55.   
    56.     public int getAge() {  
    57.         return age;  
    58.     }  
    59.   
    60.     public void setAge(int age) {  
    61.         this.age = age;  
    62.     }  
    63.   
    64.     public PropertyBean getPropertyBean() {  
    65.         return propertyBean;  
    66.     }  
    67.   
    68.     public void setPropertyBean(PropertyBean propertyBean) {  
    69.         this.propertyBean = propertyBean;  
    70.     }  
    71.   
    72.     public PropertyBean getPropertyBeanDispatcher() {  
    73.         return propertyBeanDispatcher;  
    74.     }  
    75.   
    76.     public void setPropertyBeanDispatcher(PropertyBean propertyBeanDispatcher) {  
    77.         this.propertyBeanDispatcher = propertyBeanDispatcher;  
    78.     }  
    79.   
    80.     @Override  
    81.     public String toString() {  
    82.         return "LazyBean [name=" + name + ", age=" + age + ", propertyBean="  
    83.                 + propertyBean + "]";  
    84.     }  
    85. }  
    86. </span>  


    1. <span style="font-size:14px;">package com.zghw.cglib;  
    2.   
    3. public class PropertyBean {  
    4.     private String key;  
    5.     private Object value;  
    6.     public String getKey() {  
    7.         return key;  
    8.     }  
    9.     public void setKey(String key) {  
    10.         this.key = key;  
    11.     }  
    12.     public Object getValue() {  
    13.         return value;  
    14.     }  
    15.     public void setValue(Object value) {  
    16.         this.value = value;  
    17.     }  
    18.     @Override  
    19.     public String toString() {  
    20.         return "PropertyBean [key=" + key + ", value=" + value + "]" +getClass();  
    21.     }  
    22.       
    23. }  
    24. </span>  


    1. <span style="font-size:14px;">package com.zghw.cglib;  
    2.   
    3. import net.sf.cglib.proxy.LazyLoader;  
    4.   
    5. public class ConcreteClassLazyLoader implements LazyLoader {  
    6.     /** 
    7.      * 对需要延迟加载的对象添加代理,在获取该对象属性时先通过代理类回调方法进行对象初始化。 
    8.      * 在不需要加载该对象时,只要不去获取该对象内属性,该对象就不会被初始化了(在CGLib的实现中只要去访问该对象内属性的getter方法, 
    9.      * 就会自动触发代理类回调)。 
    10.      */  
    11.     @Override  
    12.     public Object loadObject() throws Exception {  
    13.         System.out.println("before lazyLoader...");  
    14.         PropertyBean propertyBean = new PropertyBean();  
    15.         propertyBean.setKey("zghw");  
    16.         propertyBean.setValue(new TargetObject());  
    17.         System.out.println("after lazyLoader...");  
    18.         return propertyBean;  
    19.     }  
    20.   
    21. }  
    22. </span>  


    1. <span style="font-size:14px;">package com.zghw.cglib;  
    2.   
    3. import net.sf.cglib.proxy.Dispatcher;  
    4.   
    5. public class ConcreteClassDispatcher implements Dispatcher{  
    6.   
    7.     @Override  
    8.     public Object loadObject() throws Exception {  
    9.         System.out.println("before Dispatcher...");  
    10.         PropertyBean propertyBean = new PropertyBean();  
    11.         propertyBean.setKey("xxx");  
    12.         propertyBean.setValue(new TargetObject());  
    13.         System.out.println("after Dispatcher...");  
    14.         return propertyBean;  
    15.     }  
    16.   
    17. }  
    18. </span>  


    6.接口生成器InterfaceMaker

    一、作用:

    InterfaceMaker会动态生成一个接口,该接口包含指定类定义的所有方法。

    二、示例:

    1. <span style="font-size:14px;">package com.zghw.cglib;  
    2.   
    3. import java.lang.reflect.InvocationTargetException;  
    4. import java.lang.reflect.Method;  
    5.   
    6. import net.sf.cglib.proxy.Enhancer;  
    7. import net.sf.cglib.proxy.InterfaceMaker;  
    8. import net.sf.cglib.proxy.MethodInterceptor;  
    9. import net.sf.cglib.proxy.MethodProxy;  
    10.   
    11. public class TestInterfaceMaker {  
    12.   
    13.     public static void main(String[] args) throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {  
    14.         InterfaceMaker interfaceMaker =new InterfaceMaker();  
    15.         //抽取某个类的方法生成接口方法  
    16.         interfaceMaker.add(TargetObject.class);  
    17.         Class<?> targetInterface=interfaceMaker.create();  
    18.         for(Method method : targetInterface.getMethods()){  
    19.             System.out.println(method.getName());  
    20.         }  
    21.         //接口代理并设置代理接口方法拦截  
    22.         Object object = Enhancer.create(Object.class, new Class[]{targetInterface}, new MethodInterceptor(){  
    23.             @Override  
    24.             public Object intercept(Object obj, Method method, Object[] args,  
    25.                     MethodProxy methodProxy) throws Throwable {  
    26.                 if(method.getName().equals("method1")){  
    27.                     System.out.println("filter method1 ");  
    28.                     return "mmmmmmmmm";  
    29.                 }  
    30.                 if(method.getName().equals("method2")){  
    31.                     System.out.println("filter method2 ");  
    32.                     return 1111111;  
    33.                 }  
    34.                 if(method.getName().equals("method3")){  
    35.                     System.out.println("filter method3 ");  
    36.                     return 3333;  
    37.                 }  
    38.                 return "default";  
    39.             }});  
    40.         Method targetMethod1=object.getClass().getMethod("method3",new Class[]{int.class});  
    41.         int i=(int)targetMethod1.invoke(object, new Object[]{33});  
    42.         Method targetMethod=object.getClass().getMethod("method1",new Class[]{String.class});  
    43.         System.out.println(targetMethod.invoke(object, new Object[]{"sdfs"}));  
    44.     }  
    45.   
    46. }  
    47. </span>  


  • 相关阅读:
    37. Sudoku Solver(js)
    36. Valid Sudoku(js)
    35. Search Insert Position(js)
    34. Find First and Last Position of Element in Sorted Array(js)
    33. Search in Rotated Sorted Array(js)
    32. Longest Valid Parentheses(js)
    函数的柯里化
    俞敏洪:我和马云就差了8个字
    vue路由传值params和query的区别
    简述vuex的数据传递流程
  • 原文地址:https://www.cnblogs.com/zhaoxinshanwei/p/8417929.html
Copyright © 2011-2022 走看看