JDK 动态代理

  • Factory class 文件

public class ProxyFactory {

	private Object target;

	public ProxyFactory(Object target) {
		super();
		this.target = target;
	}

	/**
	* 得到代理对象
	*/
  	public Object getProxyFactory() {
		 /**
		 * 参数说明
		 * ClassLoader 类加载器
		 * Interfaces 目标类实现的所有接口数组
		 * InvocationHandler 当代理对象被创建后, 调用目标对象的方法时触发的方法回调
		 */
		return Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(), new InvocationHandler() {
			/**
			 * 
			 * @param proxy 代理对象
			 * @param method 用户调用目标的方法
			 * @param args 用户调用目标的参数
			 */
			@Override
			public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
				// 前置增强
				Object invoke = method.invoke(target, args);
				// 后置增强
				return invoke;
			}
		});
	}
}

  • mian 文件

public static void main(String[] args) {

	UserDaoImpl daoImpl = new UserDaoImpl();

	ProxyFactory proxyFactory = new ProxyFactory(daoImpl);

	UserDaoImpl daoImplFactory = (UserDaoImpl)proxyFactory.getProxyFactory();

	daoImplFactory.play();
		
}
posted @ 2022-11-15 11:33  IT_IOS_MAN  阅读(18)  评论(0编辑  收藏  举报