JDK和Cglib动态代理

来源:互联网 发布:交通安全事故数据 编辑:程序博客网 时间:2024/05/17 19:20
import java.lang.reflect.InvocationHandler;import java.lang.reflect.Method;import java.lang.reflect.Proxy;public class JDKProxyFactory implements InvocationHandler{Object target;public JDKProxyFactory(Object target) {this.target = target;}public Object createProxy() {return Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(), new InvocationHandler() {@Overridepublic Object invoke(Object proxy, Method method, Object[] args) throws Throwable {System.out.println("proxy1: " + method.getName());return method.invoke(target, args);}});}public Object createProxy2() {return Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(), this);}@Overridepublic Object invoke(Object proxy, Method method, Object[] args) throws Throwable {System.out.println("proxy2: " + method.getName());return method.invoke(target, args);}}
import java.lang.reflect.Method;import org.springframework.cglib.proxy.Enhancer;import org.springframework.cglib.proxy.MethodInterceptor;import org.springframework.cglib.proxy.MethodProxy;public class CglibProxyFactory implements MethodInterceptor {Object target;public CglibProxyFactory(Object target) {this.target = target;}public Object createProxy() {Enhancer enhancer = new Enhancer();enhancer.setSuperclass(target.getClass());enhancer.setCallback(new MethodInterceptor() {@Overridepublic Object intercept(Object proxy, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {System.out.println("CglibProxy: " + method.getName());return methodProxy.invokeSuper(proxy, args);}});return enhancer.create();}public Object createProxy2() {Enhancer enhancer = new Enhancer();enhancer.setSuperclass(target.getClass());enhancer.setCallback(this);return enhancer.create();}@Overridepublic Object intercept(Object proxy, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {System.out.println("CglibProxy2: " + method.getName());return methodProxy.invoke(target, args);}}
原创粉丝点击