示例代码
1 package DP; 2 3 import java.lang.reflect.InvocationHandler; 4 import java.lang.reflect.Method; 5 import java.lang.reflect.Proxy; 6 7 /** 8 * 通过动态代理的模式去拓展方法 9 * 10 * @author renguanyu 11 * 12 */ 13 public class DynamicProxyDemo { 14 15 public static void main(String[] args) { 16 17 /* 18 System.getProperties().put("sun.misc.ProxyGenerator.saveGeneratedFiles", "true"); 19 System.getProperties().put("jdk.proxy.ProxyGenerator.saveGeneratedFiles", "true"); 20 */ 21 22 // 示例数据 23 Emp e = new Emp("1", "liubei"); 24 // 业务对象 25 Dao dao = new DaoImpl(); 26 27 // 通过动态代理,拓展方法 28 InvocationHandler h = null; 29 30 h = new DaoInvocationHandler1(dao); 31 dao = (Dao) Proxy.newProxyInstance(ClassLoader.getSystemClassLoader(), new Class[] { Dao.class }, h); 32 33 h = new DaoInvocationHandler2(dao); 34 dao = (Dao) Proxy.newProxyInstance(ClassLoader.getSystemClassLoader(), new Class[] { Dao.class }, h); 35 36 // 业务操作 37 dao.save(e); 38 } 39 40 } 41 42 interface Dao { 43 44 void save(Emp e); 45 46 } 47 48 class DaoImpl implements Dao { 49 50 @Override 51 public void save(Emp e) { 52 53 System.out.println("save -> " + e); 54 55 } 56 57 } 58 59 class DaoInvocationHandler1 implements InvocationHandler { 60 61 Dao dao; 62 63 public DaoInvocationHandler1(Dao dao) { 64 this.dao = dao; 65 } 66 67 @Override 68 public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { 69 System.out.println("DaoInvocationHandler1 - start "); 70 method.invoke(dao, args); 71 System.out.println("DaoInvocationHandler1 - end "); 72 return null; 73 } 74 75 } 76 77 class DaoInvocationHandler2 implements InvocationHandler { 78 79 Dao dao; 80 81 public DaoInvocationHandler2(Dao dao) { 82 this.dao = dao; 83 } 84 85 @Override 86 public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { 87 System.out.println("DaoInvocationHandler2 - start "); 88 method.invoke(dao, args); 89 System.out.println("DaoInvocationHandler2 - end "); 90 return null; 91 } 92 93 } 94 95 class Emp { 96 97 String id; 98 String name; 99 100 public Emp(String id, String name) { 101 super(); 102 this.id = id; 103 this.name = name; 104 } 105 106 @Override 107 public String toString() { 108 return "Emp [id=" + id + ", name=" + name + "]"; 109 } 110 111 }