- jdk动态代理
/** * @ClassName: * @Description: Jdk的动态代理:代理对象跟目标对象要实现相同接口,拦截器必须实现InvocationHandler接口 * @yanchan [280822963@qq.com] * @date 2018/4/11 0011 14:11 */ public class IInvocationHandler implements InvocationHandler { private Object obj; public IInvocationHandler(Object obj) { this.obj = obj; } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { System.out.println("before"); method.invoke(obj, args); System.out.println("after"); return null; } public static void main(String[] args) { Man man = new Man(); IInvocationHandler var = new IInvocationHandler(man); Person proxyInstance = (Person) Proxy.newProxyInstance(man.getClass().getClassLoader(), man.getClass().getInterfaces(), var); proxyInstance.eat(); } }
2.cglib动态代理
/** * @ClassName: * @Description: cglib 动态代理: 代理对象是目标对象的子类 ,拦截器必须实现MethodInterceptor接口 * @yanchan [280822963@qq.com] * @date 2018/4/11 0011 12:09 */ public class IMethodInterceptor implements MethodInterceptor { private Object targetObj; public IMethodInterceptor(Object targetObj) { this.targetObj = targetObj; } @Override public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable { System.out.println("before"); method.invoke(targetObj, objects); System.out.println("after"); return null; } public static void main(String[] args) { IMethodInterceptor interceptor = new IMethodInterceptor(new Person()); Enhancer enhancer = new Enhancer(); enhancer.setCallback(interceptor); enhancer.setSuperclass(Person.class); Person proxyObj = (Person) enhancer.create(); proxyObj.eat(); } }