java动态代理--cglib
cglib的优点:
1. 性能高。CGLib底层采用ASM字节码生成框架,使用字节码技术生成代理类,比使用Java反射效率要高。
2. 无需实现接口。Java通过java.lang.reflect.Proxy和java.lang.reflect.InvocationHandler实现的动态代理必须实现接口,但现实中往往是没有接口的。
代码:
1. 随意定义一个类。
package pr.cgl.cglib;
/**
* Created by LL on 2015/8/27.
*/
public class Tank {
public void move(){
System.out.println("Tank is moving...");
}
public void action(){
System.out.println("Tank is start firing...");
}
}
2. 实现
package pr.cgl.cglib;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;
import java.lang.reflect.Method;
/**
* Created by LL on 2015/8/27.
*/
public class CglibProxy implements MethodInterceptor {
//要代理的原始对象
private Object obj;
public Object createProxy(Object target) {
this.obj = target;
Enhancer enhancer = new Enhancer();
enhancer.setSuperclass(target.getClass());// 设置代理目标
enhancer.setCallback(new CglibProxy());// 设置回调
enhancer.setClassLoader(target.getClass().getClassLoader());
return enhancer.create();
}
@Override
public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
Long start = System.currentTimeMillis();
System.out.println("start="+start);
Object result = methodProxy.invokeSuper(o, objects);
Long end = System.currentTimeMillis();
System.out.println("end="+end);
System.out.println("time spent :"+((end - start))+" "+result);
return result;
}
}
3. 测试
package pr.cgl.cglib;
/**
* Created by LL on 2015/8/27.
*/
public class Test3 {
public static void main(String[] args) {
Tank tank = new Tank();
CglibProxy proxy = new CglibProxy();
Tank t = (Tank)proxy.createProxy(tank);
t.action();
}
}
输出:
start=1440662005592
Tank is start firing...
end=1440662005605
time spent :13 null