动态代理-jdk代理
实现 InvocationHandler接口(代理处理器)
1 package cn.learn.proxy; 2 3 import java.lang.reflect.InvocationHandler; 4 import java.lang.reflect.Method; 5 6 /** 7 * 代理处理器类 8 */ 9 public class JdkDynamicProxyHandler implements InvocationHandler { 10 private Object assignedObject = null; 11 12 public JdkDynamicProxyHandler(Object assignedObject) { 13 this.assignedObject = assignedObject; 14 } 15 16 @Override 17 public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { 18 System.out.println("调用目标方法前,增强."); 19 Object result = method.invoke(assignedObject, args); 20 System.out.println("调用目标方法后,增强."); 21 return result; 22 } 23 }
代理处理器,接受目标对象
1 JdkDynamicProxyHandler jdkDynamicProxyHandler = new JdkDynamicProxyHandler(iUserService);
创建代理
1 IUserService proxy = (IUserService)Proxy.newProxyInstance( 2 iUserService.getClass().getClassLoader() // 3 , iUserService.getClass().getInterfaces() // 代理类需要实现的接口(代理类需要与目标类实现相同接口) cn.learn.proxy.IUserService 4 , jdkDynamicProxyHandler); // 代理处理器
调用代理对象
1 proxy.sayHi("good morning");