java 动态代理 CGLIB AOP基础

什么是java动态代理?先说说静态代理吧,在程序运行之前就编译好的代理类,动态代理就是运行时生成搞些小动作。举个不恰当的例子:本来去学校读书,父母希望是专心听老师讲课(静态代理),但坐在教室心里总想着那个ta,传纸条,谈朋友等,结果课也上好了,朋友也谈了,多美好的事。

 

由Java的反射机制完成,也是学习spring的基础。

不多说,下面代码片段将实现一个计算器的日志,用代理实现。

 

/**
 * 接口
 * @author tangyi
 */
public interface ICaclulator {
	@Deprecated
	int add(int i, int j);
	int sub(int i, int j);
	int mul(int i, int j);
	int dev(int i, int j); 
}

 

/**
 * 接口实现类 具体业务方法
 * @author tangyi
 */
public class CaclulatorImpl implements ICaclulator {

	@Override
	public int add(int i, int j) {
		int result = i + j;
		return result;
	}

	@Override
	public int sub(int i, int j) {
		int result = i - j;
		return result;
	}

	@Override
	public int mul(int i, int j) {
		int result = i * j;
		return result;
	}

	@Override
	public int dev(int i, int j) {
		int result = i / j;
		return result;
	}

}

 

/**
 * @see 日志代理类
 * @author tangyi
 *
 */
public class CaclulatorLogProxy {
	private ICaclulator target;
	
	/**
	 * 构造器
	 */
	public CaclulatorLogProxy(ICaclulator target) {
		this.target = target;
	}
	
	public Object getLoggingProxy(){
		ICaclulator proxy = null;
		//代理类的类加载器
		ClassLoader loader = target.getClass().getClassLoader();
		//代理对象类型
		Class[] interfaces = new Class[]{ICaclulator.class};
		//当调用代理对象中的方法时
		InvocationHandler h = new InvocationHandler() {
			/**
			 * proxy:正在返回的那个代理对象;
			 * method:正在被调用的方法;
			 * args:调用方法时,传入的参数;
			 */
			@Override
			public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
				String methodName = method.getName();
				System.out.println("The method " + methodName + " begin with " + Arrays.asList(args));
				Object result = method.invoke(target, args);
				System.out.println("The method " + methodName + " end with " + result);
				return result;
			}
		};
		return Proxy.newProxyInstance(loader, interfaces, h);
	}
}

 

**
 * @author tangyi
 *
 */
public class Main {
	public static void main(String[] args) {
		ICaclulator target = new CaclulatorImpl();
		ICaclulator proxy = (ICaclulator) new CaclulatorLogProxy(target).getLoggingProxy();
		System.out.println(proxy.getClass().getName());
		int result = proxy.add(1, 2);
		System.out.println("-->>" + result);

		result = proxy.sub(4, 2);
		System.out.println("-->>" + result);
	}
}

 测试结果:

com.sun.proxy.$Proxy0
The method add begin with [1, 2]
The method add end with 3
-->>3
The method sub begin with [4, 2]
The method sub end with 2
-->>2

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值