码迷,mamicode.com
首页 > 其他好文 > 详细

动态代理 - 示例1

时间:2020-05-24 11:30:32      阅读:37      评论:0      收藏:0      [点我收藏+]

标签: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 + "]";
	}

}

  

动态代理 - 示例1

标签:throws   tar   out   示例   owa   his   lang   dem   object   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!