使用动态代理来记录日志(计算器例子)

1.创建计算器接口和实现类

public interface Calculator {

	public int add (int i,int j);
	
	public int sub (int i,int j);
}
public class CalculatorImpl implements Calculator{

	@Override
	public int add(int i, int j) {
		// TODO Auto-generated method stub
		return i+j;
	}

	@Override
	public int sub(int i, int j) {
		// TODO Auto-generated method stub
		return i-j;
	}

}

2.创建动态代理类

public class CalculatorProxy {
	
	private Calculator target;

	public CalculatorProxy(Calculator calculator) {
		super();
		this.target = calculator;  //注入目标对象
	}
	
	public Object getProxy() {
		
		Object proxy;
		ClassLoader loader = target.getClass().getClassLoader();
		Class<?>[] interfaces = target.getClass().getInterfaces();
		
		proxy = Proxy.newProxyInstance(loader, interfaces, new InvocationHandler() {
			
			private Object result;

			@Override
			public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
				// TODO Auto-generated method stub
				String methodName = method.getName();
				//记录日记
				System.out.println("LoggingProxy => the method "+methodName+" begin with "+Arrays.asList(args));
				//调用目标对象的目标方法
				result = method.invoke(target, args);
				//记录日记
				System.out.println("LoggingProxy => the method "+methodName+" end with "+result);
				return result;
			}
		});
		
		return proxy;
	}

}

3.动态代理测试

public class Main {

	public static void main(String[] args) {
		
		Calculator target = new CalculatorImpl();
		//将记录日志和被代理对象的代码组装在一起
		Object proxy = new CalculatorProxy(target).getProxy();
		
		Calculator calculatorProxy = (Calculator) proxy;
		
		int result;
		result = calculatorProxy.add(1, 3);
		System.out.println(result);
		
		result = calculatorProxy.sub(4, 2);
		System.out.println(result);
		
	}
}

运行结果

LoggingProxy => the method add begin with [1, 3]
LoggingProxy => the method add end with 4
4
LoggingProxy => the method sub begin with [4, 2]
LoggingProxy => the method sub end with 2
2
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值