最近分析的java的动态代理,结合回顾了cglib,写了个case,留作备忘。
动态代理和cglib的对比网上一堆:
cglib是继承复用,对asm进行了封装,因此对原类中的final方法有点无能为力,而且基于asm重新生成class类,虽然免去了部分对java中类的理解,技术也略复杂,但是不必像动态那样需要定义一个接口,从而Proxy才能根据此接口生成相应的代理类,在这个角度显得更加简洁。
以下是测试case,留作备份。
import net.sf.cglib.proxy.*;
import java.lang.reflect.Method;
/**
* Created by
*/
public class CglibProxyTest {
final private static class MethodInterceptorTest implements MethodInterceptor{
private String password;
MethodInterceptorTest(String password){
this.password = password;
}
@Override
public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
System.out.println("start");
System.out.println("method name:" + method.getName());
if("123456".equals(password)){
methodProxy.invokeSuper(o, objects);
}else {
System.err.println("no permission!");
}
System.out.println("end");
return null;
}
}
private static class MethodTest{
public MethodTest(){
}
public void test1(){
System.out.println("test1");
}
public void test2(){
System.out.println("test2");
}
public void test(){
System.out.println("hello world");
}
}
private static class CallbackFilterTest implements CallbackFilter{
@Override
public int accept(Method method) {
if("test1".equals(method.getName())){
return 0;
}else {
return 1;
}
}
}
private static class CglibProxyFactory{
public static MethodTest getMethod(MethodInterceptorTest methodInterceptorTest){
Enhancer enhancer = new Enhancer();
enhancer.setSuperclass(MethodTest.class);
// enhancer.setCallback(methodInterceptorTest);
enhancer.setCallbacks(new Callback[]{methodInterceptorTest, NoOp.INSTANCE});
enhancer.setCallbackFilter(new CallbackFilterTest());
MethodTest methodTest = (MethodTest)enhancer.create();
return methodTest;
}
}
public static void main(String[] args){
MethodInterceptorTest methodInterceptorTest = new MethodInterceptorTest("123456");
MethodTest methodTest = CglibProxyFactory.getMethod(methodInterceptorTest);
methodTest.test1();
methodTest.test2();
}
}