标签:throws tar out 示例 owa his lang dem object
示例代码
package DP; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; interface Dao { void save(Emp e); } class DaoImpl implements Dao { @Override public void save(Emp e) { System.out.println("save -> " + e); } } class DaoInvocationHandler1 implements InvocationHandler { Dao dao; public DaoInvocationHandler1(Dao dao) { this.dao = dao; } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { System.out.println("DaoInvocationHandler1 - start "); method.invoke(dao, args); System.out.println("DaoInvocationHandler1 - end "); return null; } } class DaoInvocationHandler2 implements InvocationHandler { Dao dao; public DaoInvocationHandler2(Dao dao) { this.dao = dao; } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { System.out.println("DaoInvocationHandler2 - start "); method.invoke(dao, args); System.out.println("DaoInvocationHandler2 - end "); return null; } } /** * 通过铜带代理得方式去拓展方法 * * @author renguanyu * */ public class DynamicProxyDemo { public static void main(String[] args) { // 示例数据 Emp e = new Emp("1", "liubei"); // 业务对象 Dao dao = new DaoImpl(); // 通过动态代理,拓展方法 InvocationHandler h = null; h = new DaoInvocationHandler1(dao); dao = (Dao) Proxy.newProxyInstance(ClassLoader.getSystemClassLoader(), new Class[] { Dao.class }, h); h = new DaoInvocationHandler2(dao); dao = (Dao) Proxy.newProxyInstance(ClassLoader.getSystemClassLoader(), new Class[] { Dao.class }, h); // 业务操作 dao.save(e); } } class Emp { String id; String name; public Emp(String id, String name) { super(); this.id = id; this.name = name; } @Override public String toString() { return "Emp [id=" + id + ", name=" + name + "]"; } }
标签:throws tar out 示例 owa his lang dem object
原文地址:https://www.cnblogs.com/renguanyu/p/12946005.html