JDK动态代理与CGLIB代理
JDK动态代理只能用于有接口的类的代理, 主要用到java.lang.reflect.Proxy类与java.lang.reflect.InvocationHandler接口.
InvocationHandler 用于增强目标类.
Interface object = (Interface) Proxy.newProxyInstance(loader, interfaces, InvocationHandler);
- Parameters:
- loader the class loader to define the proxy class
- interfaces the list of interfaces for the proxy class to implement
- InvocationHandler the invocation handler to dispatch method invocations to
/* JDK dynamic Proxy */ final Target proxyTarget = new Target(); ClassLoader loader = Thread.currentThread().getContextClassLoader(); try { Class[] clas = {TargetInterface.class}; TargetInterface instance = (TargetInterface)Proxy.newProxyInstance(loader, clas, new InvocationHandler() { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { System.out.println("Before proxy."); Object ret = method.invoke(proxyTarget, args); System.out.println("After proxy."); return ret; } });
CGLIB弥补了JDK动态代理只能用于有接口类的代理的缺陷, 可以为任何类代理, 主要用到net.sf.cglib.proxy.Enhancer和net.sf.cglib.proxy.MethodInterceptor接口
MethodInterceptor用于增强目标类.
/*
CGLIB Proxy
*/
final Target proxyTarget = new Target();
Enhancer enhancer = new Enhancer();
// enhancer.setSuperclass(proxyTarget.getClass());
// enhancer.setCallback(new CGlibProxy(proxyTarget));
// Target target = (Target)enhancer.create();
Target target = (Target)enhancer.create(Target.class, new MethodInterceptor(){
@Override
public Object intercept(Object arg0, Method arg1, Object[] arg2,
MethodProxy arg3) throws Throwable {
System.out.println("Before proxy.");
Object ret = arg1.invoke(proxyTarget, arg2);
System.out.println("After proxy.");
return ret;
}
});
浙公网安备 33010602011771号