首页 > 其他 > 详细

动态代理 - 示例1

时间:2020-05-24 11:09:52      阅读:51      评论:0      收藏:0      [点我收藏+]

 示例代码

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

原文:https://www.cnblogs.com/renguanyu/p/12946005.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!