动态代理 - 示例1
Posted renguanyu
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了动态代理 - 示例1相关的知识,希望对你有一定的参考价值。
示例代码
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 + "]"; } }
以上是关于动态代理 - 示例1的主要内容,如果未能解决你的问题,请参考以下文章