原生动态代理

来张图开开胃


package com.hous.math;

public interface ArithmeticCalculator {
	public int add(int i, int j);

	public int sub(int i, int j);

	public int mul(int i, int j);

	public int div(int i, int j);
}
package com.hous.math;

public class ArithmeticCalculatorImpl implements ArithmeticCalculator{

	@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 div(int i, int j) {
		int result = i / j;
		return result;
	}

}

 
 

package com.hous.test;

import com.hous.math.ArithmeticCalculator;
import com.hous.math.ArithmeticCalculatorImpl;
import com.hous.math.ArithmeticCalculatorLoggingProxy;

public class Math {
	public static void main(String[] args) {
		ArithmeticCalculator arithmeticCalculator = new ArithmeticCalculatorImpl();
		
		ArithmeticCalculator proxy = new ArithmeticCalculatorLoggingProxy(arithmeticCalculator).getLoggingProxy();
		
		System.out.println(proxy.add(12, 23));
		
	}
}
package com.hous.math;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Arrays;

public class ArithmeticCalculatorLoggingProxy {
private ArithmeticCalculator target;

public ArithmeticCalculatorLoggingProxy(ArithmeticCalculator target) {
	this.target = target;
}

public ArithmeticCalculator getLoggingProxy(){
	ArithmeticCalculator proxy = null;
//	代理对象由哪个类加载器负责加载
	ClassLoader loader = target.getClass().getClassLoader();
//	代理对象的类型,即其中有哪些方法
	Class[] interfaces = new Class[]{ArithmeticCalculator.class};
//	当调用代理对象方法是,执行该代码
	InvocationHandler handler = new InvocationHandler() {
		
		/* *
		 * proxy:返回哪个代理对象,在invoke方法内不适用
		 * method:被调用的方法
		 * args:调用方法时的传入参数
		 */
		@Override
		public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
			
			String methodName = method.getName();
			//日志
			System.out.println("The method " + methodName + " begins with " + Arrays.asList(args));
			//执行方法
			Object result = method.invoke(target, args);
			//日志
			System.out.println("The method " + methodName + " end with " + result);
			
			return result;
		}
	};
	proxy = (ArithmeticCalculator) Proxy.newProxyInstance(loader, interfaces, handler);
	
	return proxy;
}

}

猜你喜欢

转载自shuizhongyue.iteye.com/blog/2292709
今日推荐