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

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

你可能感兴趣的:(Java,java,开发语言)