一、什么是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 1 package com.zghw.cglib; 2 2 3 3 /** 4 4 * 没有实现接口,需要CGlib动态代理的目标类 5 5 * 6 6 * @author zghw 7 7 * 8 8 */ 9 9 public class TargetObject { 1010 public String method1(String paramName) { 1111 return paramName; 1212 } 1313 1414 public int method2(int count) { 1515 return count; 1616 } 1717 1818 public int method3(int count) { 1919 return count; 2020 } 2121 2222 @Override 2323 public String toString() { 2424 return "TargetObject []"+ getClass(); 2525 } 2626 }</span>
2、拦截器:
定义一个拦截器。在调用目标方法时,CGLib会回调MethodInterceptor接口方法拦截,来实现你自己的代理逻辑,类似于JDK中的InvocationHandler接口。
1 1 package com.zghw.cglib; 2 2 3 3 import java.lang.reflect.Method; 4 4 import net.sf.cglib.proxy.MethodInterceptor; 5 5 import net.sf.cglib.proxy.MethodProxy; 6 6 /** 7 7 * 目标对象拦截器,实现MethodInterceptor 8 8 * @author zghw 9 9 * 1010 */ 1111 public class TargetInterceptor implements MethodInterceptor{ 1212 /** 1313 * 重写方法拦截在方法前和方法后加入业务 1414 * Object obj为目标对象 1515 * Method method为目标方法 1616 * Object[] params 为参数, 1717 * MethodProxy proxy CGlib方法代理对象 1818 */ 1919 @Override 2020 public Object intercept(Object obj, Method method, Object[] params, 2121 MethodProxy proxy) throws Throwable { 2222 System.out.println("调用前"); 2323 Object result = proxy.invokeSuper(obj, params); 2424 System.out.println(" 调用后"+result); 2525 return result; 2626 } 2727 }
参数:Object为由CGLib动态生成的代理类实例,Method为上文中实体类所调用的被代理的方法引用,Object[]为参数值列表,MethodProxy为生成的代理类对方法的代理引用。
返回:从代理实例的方法调用返回的值。
其中,proxy.invokeSuper(obj,arg):
调用代理类实例上的proxy方法的父类方法(即实体类TargetObject中对应的方法)
在这个示例中,只在调用被代理类方法前后各打印了一句话,当然实际编程中可以是其它复杂逻辑。
3、生成动态代理类:
1 1 package com.zghw.cglib; 2 2 3 3 import net.sf.cglib.proxy.Callback; 4 4 import net.sf.cglib.proxy.CallbackFilter; 5 5 import net.sf.cglib.proxy.Enhancer; 6 6 import net.sf.cglib.proxy.NoOp; 7 7 8 8 public class TestCglib { 9 9 public static void main(String args[]) { 1010 Enhancer enhancer =new Enhancer(); 1111 enhancer.setSuperclass(TargetObject.class); 1212 enhancer.setCallback(new TargetInterceptor()); 1313 TargetObject targetObject2=(TargetObject)enhancer.create(); 1414 System.out.println(targetObject2); 1515 System.out.println(targetObject2.method1("mmm1")); 1616 System.out.println(targetObject2.method2(100)); 1717 System.out.println(targetObject2.method3(200)); 1818 } 1919 }
这里Enhancer类是CGLib中的一个字节码增强器,它可以方便的对你想要处理的类进行扩展,以后会经常看到它。
首先将被代理类TargetObject设置成父类,然后设置拦截器TargetInterceptor,最后执行enhancer.create()动态生成一个代理类,并从Object强制转型成父类型TargetObject。
最后,在代理类上调用方法.
4、回调过滤器CallbackFilter
一、作用
在CGLib回调时可以设置对不同方法执行不同的回调逻辑,或者根本不执行回调。
在JDK动态代理中并没有类似的功能,对InvocationHandler接口方法的调用对代理类内的所以方法都有效。
定义实现过滤器CallbackFilter接口的类:
1 1 package com.zghw.cglib; 2 2 3 3 import java.lang.reflect.Method; 4 4 import net.sf.cglib.proxy.CallbackFilter; 5 5 /** 6 6 * 回调方法过滤 7 7 * @author zghw 8 8 * 9 9 */ 1010 public class TargetMethodCallbackFilter implements CallbackFilter { 1111 /** 1212 * 过滤方法 1313 * 返回的值为数字,代表了Callback数组中的索引位置,要到用的Callback 1414 */ 1515 @Override 1616 public int accept(Method method) { 1717 if(method.getName().equals("method1")){ 1818 System.out.println("filter method1 ==0"); 1919 return 0; 2020 } 2121 if(method.getName().equals("method2")){ 2222 System.out.println("filter method2 ==1"); 2323 return 1; 2424 } 2525 if(method.getName().equals("method3")){ 2626 System.out.println("filter method3 ==2"); 2727 return 2; 2828 } 2929 return 0; 3030 } 3131 }
其中return值为被代理类的各个方法在回调数组Callback[]中的位置索引(见下文)。
1 1 package com.zghw.cglib; 2 2 3 3 import net.sf.cglib.proxy.Callback; 4 4 import net.sf.cglib.proxy.CallbackFilter; 5 5 import net.sf.cglib.proxy.Enhancer; 6 6 import net.sf.cglib.proxy.NoOp; 7 7 8 8 public class TestCglib { 9 9 public static void main(String args[]) { 1010 Enhancer enhancer =new Enhancer(); 1111 enhancer.setSuperclass(TargetObject.class); 1212 CallbackFilter callbackFilter = new TargetMethodCallbackFilter(); 1313 1414 /** 1515 * (1)callback1:方法拦截器 1616 (2)NoOp.INSTANCE:这个NoOp表示no operator,即什么操作也不做,代理类直接调用被代理的方法不进行拦截。 1717 (3)FixedValue:表示锁定方法返回值,无论被代理类的方法返回什么值,回调方法都返回固定值。 1818 */ 1919 Callback noopCb=NoOp.INSTANCE; 2020 Callback callback1=new TargetInterceptor(); 2121 Callback fixedValue=new TargetResultFixed(); 2222 Callback[] cbarray=new Callback[]{callback1,noopCb,fixedValue}; 2323 //enhancer.setCallback(new TargetInterceptor()); 2424 enhancer.setCallbacks(cbarray); 2525 enhancer.setCallbackFilter(callbackFilter); 2626 TargetObject targetObject2=(TargetObject)enhancer.create(); 2727 System.out.println(targetObject2); 2828 System.out.println(targetObject2.method1("mmm1")); 2929 System.out.println(targetObject2.method2(100)); 3030 System.out.println(targetObject2.method3(100)); 3131 System.out.println(targetObject2.method3(200)); 3232 } 3333 } 34 35 1 package com.zghw.cglib; 36 2 37 3 import net.sf.cglib.proxy.FixedValue; 38 4 /** 39 5 * 表示锁定方法返回值,无论被代理类的方法返回什么值,回调方法都返回固定值。 40 6 * @author zghw 41 7 * 42 8 */ 43 9 public class TargetResultFixed implements FixedValue{ 4410 4511 /** 4612 * 该类实现FixedValue接口,同时锁定回调值为999 4713 * (整型,CallbackFilter中定义的使用FixedValue型回调的方法为getConcreteMethodFixedValue,该方法返回值为整型)。 4814 */ 4915 @Override 5016 public Object loadObject() throws Exception { 5117 System.out.println("锁定结果"); 5218 Object obj = 999; 5319 return obj; 5420 } 5521 5622 }
5.延迟加载对象
一、作用:
说到延迟加载,应该经常接触到,尤其是使用Hibernate的时候,本篇将通过一个实例分析延迟加载的实现方式。
LazyLoader接口继承了Callback,因此也算是CGLib中的一种Callback类型。
另一种延迟加载接口Dispatcher。
Dispatcher接口同样继承于Callback,也是一种回调类型。
但是Dispatcher和LazyLoader的区别在于:LazyLoader只在第一次访问延迟加载属性时触发代理类回调方法,而Dispatcher在每次访问延迟加载属性时都会触发代理类回调方法。
二、示例:
首先定义一个实体类LoaderBean,该Bean内有一个需要延迟加载的属性PropertyBean。
1 1 package com.zghw.cglib; 2 2 3 3 import net.sf.cglib.proxy.Enhancer; 4 4 5 5 public class LazyBean { 6 6 private String name; 7 7 private int age; 8 8 private PropertyBean propertyBean; 9 9 private PropertyBean propertyBeanDispatcher; 1010 1111 public LazyBean(String name, int age) { 1212 System.out.println("lazy bean init"); 1313 this.name = name; 1414 this.age = age; 1515 this.propertyBean = createPropertyBean(); 1616 this.propertyBeanDispatcher = createPropertyBeanDispatcher(); 1717 } 1818 1919 2020 2121 /** 2222 * 只第一次懒加载 2323 * @return 2424 */ 2525 private PropertyBean createPropertyBean() { 2626 /** 2727 * 使用cglib进行懒加载 对需要延迟加载的对象添加代理,在获取该对象属性时先通过代理类回调方法进行对象初始化。 2828 * 在不需要加载该对象时,只要不去获取该对象内属性,该对象就不会被初始化了(在CGLib的实现中只要去访问该对象内属性的getter方法, 2929 * 就会自动触发代理类回调)。 3030 */ 3131 Enhancer enhancer = new Enhancer(); 3232 enhancer.setSuperclass(PropertyBean.class); 3333 PropertyBean pb = (PropertyBean) enhancer.create(PropertyBean.class, 3434 new ConcreteClassLazyLoader()); 3535 return pb; 3636 } 3737 /** 3838 * 每次都懒加载 3939 * @return 4040 */ 4141 private PropertyBean createPropertyBeanDispatcher() { 4242 Enhancer enhancer = new Enhancer(); 4343 enhancer.setSuperclass(PropertyBean.class); 4444 PropertyBean pb = (PropertyBean) enhancer.create(PropertyBean.class, 4545 new ConcreteClassDispatcher()); 4646 return pb; 4747 } 4848 public String getName() { 4949 return name; 5050 } 5151 5252 public void setName(String name) { 5353 this.name = name; 5454 } 5555 5656 public int getAge() { 5757 return age; 5858 } 5959 6060 public void setAge(int age) { 6161 this.age = age; 6262 } 6363 6464 public PropertyBean getPropertyBean() { 6565 return propertyBean; 6666 } 6767 6868 public void setPropertyBean(PropertyBean propertyBean) { 6969 this.propertyBean = propertyBean; 7070 } 7171 7272 public PropertyBean getPropertyBeanDispatcher() { 7373 return propertyBeanDispatcher; 7474 } 7575 7676 public void setPropertyBeanDispatcher(PropertyBean propertyBeanDispatcher) { 7777 this.propertyBeanDispatcher = propertyBeanDispatcher; 7878 } 7979 8080 @Override 8181 public String toString() { 8282 return "LazyBean [name=" + name + ", age=" + age + ", propertyBean=" 8383 + propertyBean + "]"; 8484 } 8585 } 86 87 1 package com.zghw.cglib; 88 2 89 3 public class PropertyBean { 90 4 private String key; 91 5 private Object value; 92 6 public String getKey() { 93 7 return key; 94 8 } 95 9 public void setKey(String key) { 9610 this.key = key; 9711 } 9812 public Object getValue() { 9913 return value; 10014 } 10115 public void setValue(Object value) { 10216 this.value = value; 10317 } 10418 @Override 10519 public String toString() { 10620 return "PropertyBean [key=" + key + ", value=" + value + "]" +getClass(); 10721 } 10822 10923 } 110 111 1 package com.zghw.cglib; 112 2 113 3 import net.sf.cglib.proxy.LazyLoader; 114 4 115 5 public class ConcreteClassLazyLoader implements LazyLoader { 116 6 /** 117 7 * 对需要延迟加载的对象添加代理,在获取该对象属性时先通过代理类回调方法进行对象初始化。 118 8 * 在不需要加载该对象时,只要不去获取该对象内属性,该对象就不会被初始化了(在CGLib的实现中只要去访问该对象内属性的getter方法, 119 9 * 就会自动触发代理类回调)。 12010 */ 12111 @Override 12212 public Object loadObject() throws Exception { 12313 System.out.println("before lazyLoader..."); 12414 PropertyBean propertyBean = new PropertyBean(); 12515 propertyBean.setKey("zghw"); 12616 propertyBean.setValue(new TargetObject()); 12717 System.out.println("after lazyLoader..."); 12818 return propertyBean; 12919 } 13020 13121 } 132 133 1 package com.zghw.cglib; 134 2 135 3 import net.sf.cglib.proxy.Dispatcher; 136 4 137 5 public class ConcreteClassDispatcher implements Dispatcher{ 138 6 139 7 @Override 140 8 public Object loadObject() throws Exception { 141 9 System.out.println("before Dispatcher..."); 14210 PropertyBean propertyBean = new PropertyBean(); 14311 propertyBean.setKey("xxx"); 14412 propertyBean.setValue(new TargetObject()); 14513 System.out.println("after Dispatcher..."); 14614 return propertyBean; 14715 } 14816 14917 }
6.接口生成器InterfaceMaker
一、作用:
InterfaceMaker会动态生成一个接口,该接口包含指定类定义的所有方法。
二、示例:
1 1 package com.zghw.cglib; 2 2 3 3 import java.lang.reflect.InvocationTargetException; 4 4 import java.lang.reflect.Method; 5 5 6 6 import net.sf.cglib.proxy.Enhancer; 7 7 import net.sf.cglib.proxy.InterfaceMaker; 8 8 import net.sf.cglib.proxy.MethodInterceptor; 9 9 import net.sf.cglib.proxy.MethodProxy; 1010 1111 public class TestInterfaceMaker { 1212 1313 public static void main(String[] args) throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { 1414 InterfaceMaker interfaceMaker =new InterfaceMaker(); 1515 //抽取某个类的方法生成接口方法 1616 interfaceMaker.add(TargetObject.class); 1717 Class<?> targetInterface=interfaceMaker.create(); 1818 for(Method method : targetInterface.getMethods()){ 1919 System.out.println(method.getName()); 2020 } 2121 //接口代理并设置代理接口方法拦截 2222 Object object = Enhancer.create(Object.class, new Class[]{targetInterface}, new MethodInterceptor(){ 2323 @Override 2424 public Object intercept(Object obj, Method method, Object[] args, 2525 MethodProxy methodProxy) throws Throwable { 2626 if(method.getName().equals("method1")){ 2727 System.out.println("filter method1 "); 2828 return "mmmmmmmmm"; 2929 } 3030 if(method.getName().equals("method2")){ 3131 System.out.println("filter method2 "); 3232 return 1111111; 3333 } 3434 if(method.getName().equals("method3")){ 3535 System.out.println("filter method3 "); 3636 return 3333; 3737 } 3838 return "default"; 3939 }}); 4040 Method targetMethod1=object.getClass().getMethod("method3",new Class[]{int.class}); 4141 int i=(int)targetMethod1.invoke(object, new Object[]{33}); 4242 Method targetMethod=object.getClass().getMethod("method1",new Class[]{String.class}); 4343 System.out.println(targetMethod.invoke(object, new Object[]{"sdfs"})); 4444 } 4545 4646 }