cglib是个好东东,说牛刀,是因为它很强大,用途很广。小试,是因为仅仅用它做了个类似hello world的小程序。
cglib是Spring、Hibernate依赖的核心包,但是cglib还算不上最底层的,因为它是在asm包之上做了封装,以增强易用性。据了解,Hibernate3.2已经不再依赖cglib了,而直接依赖asm。这些都不影响cglib的强大功能。
很希望将spring、JDK、cglib的动态代理三者放到一起做个比较(实际上,spring、jdk的代理已经比较过了),也许是地震原因,心情一直没有平静下来,无心去写。下面就先给个地震前例子看看,因为很简单,所以就不细说了,有空了再做深入研究。
其实所有代理道理都是一样,就是通过代理对象去调用目标对象,并且在代理对象中做点“手脚”--加入一些其他操作。
下面看例子:
目标对象
/**
* Created by IntelliJ IDEA.<br>
* <b>User</b>: leizhimin<br>
* <b>Date</b>: 2008-5-14 0:38:35<br>
* <b>Note</b>: Please add comment here!
*/
public class Target {
public String execute() {
String message = "----------test()----------";
System.out.println(message);
return message;
}
}
拦截器
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;
import java.lang.reflect.Method;
/**
* Created by IntelliJ IDEA.<br>
* <b>User</b>: leizhimin<br>
* <b>Date</b>: 2008-5-14 0:39:08<br>
* <b>Note</b>: Please add comment here!
*/
public class MyMethodInterceptor implements MethodInterceptor {
public Object intercept(Object object, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
System.out.println(">>>MethodInterceptor start...");
Object result = methodProxy.invokeSuper(object,args);
System.out.println(">>>MethodInterceptor ending...");
return "hahahh";
}
}
import net.sf.cglib.proxy.Enhancer;
/**
* Created by IntelliJ IDEA.<br>
* <b>User</b>: leizhimin<br>
* <b>Date</b>: 2008-5-14 0:41:01<br>
* <b>Note</b>: Please add comment here!
*/
public class TestCglibProxy {
public static void main(String rags[]){
Target target = new Target();
TestCglibProxy test = new TestCglibProxy();
Target proxyTarget = (Target)test.createProxy(Target.class);
String res=proxyTarget.execute();
System.out.println(res);
}
public Object createProxy(Class targetClass){
Enhancer enhancer = new Enhancer();
enhancer.setSuperclass(targetClass);
enhancer.setCallback(new MyMethodInterceptor());
return enhancer.create();
}
}
运行结果:
C:\classes>java -cp .;C:\classes\cglib-nodep-2.1_3.jar TestCglibProxy
>>>MethodInterceptor start...
----------test()----------
>>>MethodInterceptor ending...
hahahh
C:\classes>