动态代理
1 public interface UserManager { 2 public void addUser(String name); 3 }
1 public class UserManagerImpl implements UserManager { 2 3 @Override 4 public void addUser(String name) { 5 6 System.out.println(" Add User " + name); 7 } 8 9 }
InvocationHandler
1 /** 2 * 实现自己的InvocationHandler 3 * 4 * @author zyb 5 * @since 2012-8-9 6 * 7 */ 8 public class MyInvocationHandler implements InvocationHandler { 9 10 // 目标对象 11 private Object target; 12 13 /** 14 * 构造方法 15 * 16 * @param target 17 * 目标对象 18 */ 19 public MyInvocationHandler(Object target) { 20 super(); 21 this.target = target; 22 } 23 24 /** 25 * 执行目标对象的方法 26 */ 27 public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { 28 29 // 执行目标对象的方法 30 Object result = null; 31 try { 32 // 在目标对象的方法执行之前简单的打印一下 33 System.out.println("------------------before------------------"); 34 35 result = method.invoke(target, args); 36 37 // 在目标对象的方法执行之后简单的打印一下 38 System.out.println("-------------------after------------------"); 39 } catch (Exception e) { 40 // TODO Auto-generated catch block 41 e.printStackTrace(); 42 } 43 44 return result; 45 } 46 47 }
测试:
1 public class Client { 2 public static void main(String[] args) { 3 4 UserManager userManager = new UserManagerImpl(); 5 6 // 实例化InvocationHandler 7 MyInvocationHandler invocationHandler = new MyInvocationHandler(userManager); 8 // 根据目标对象生成代理对象 9 UserManager userManagerProxy =(UserManager) Proxy.newProxyInstance(userManager.getClass().getClassLoader(),userManager.getClass().getInterfaces(),invocationHandler); 10 // 调用代理对象的方法 11 userManagerProxy.addUser(" zhangsan"); 12 13 14 } 15 16 }
结果:
------------------before------------------
Add User zhangsan
-------------------after------------------