前言
关于动态代理
JDK动态代理
public class JDKProxy implements InvocationHandler {
private Object target;
public JDKProxy(Object target) {
this.target = target;
}
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("before do something");
method.invoke(target, args);
System.out.println("after do something");
return proxy;
}
}
public class ProxyPratice {
public static void main(String[] args) {
ProxyTarget proxyTarget = new ProxyTarget();
//JDK代理
ProxyInterface proxyInterface = (ProxyInterface) Proxy.newProxyInstance(ProxyPratice.class.getClassLoader(), new Class[]{ProxyInterface.class}, new JDKProxy(proxyTarget));
proxyInterface.doSomething();
}
}
CGLIB动态代理
public class CglibProxy implements MethodInterceptor {
private Object target;
public CglibProxy(Object target) {
this.target = target;
}
@Override
public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
System.out.println("before do something");
method.invoke(target, objects);
System.out.println("after do something");
return null;
}
}
public class ProxyPratice {
public static void main(String[] args) {
ProxyTarget proxyTarget = new ProxyTarget();
//CGLIB
Enhancer enhancer = new Enhancer();
enhancer.setSuperclass(ProxyInterface.class);
enhancer.setCallback(new CglibProxy(proxyTarget));
ProxyInterface proxyInterface2 = (ProxyInterface)enhancer.create();
proxyInterface2.doSomething();
}
}
区别
java动态代理是利用反射机制生成一个实现代理接口的匿名类,在调用具体方法前调用InvokeHandler来处理。所以只能对实现了接口的类生成代理,而不能针对类。
cglib动态代理是利用asm开源包,对代理对象类的class文件加载进来,通过修改其字节码生成子类来处理,覆盖其中的方法(继承)。所以CGLib不能对声明为final的方法进行代理。