原生动态代理

来张图开开胃


 

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;
}

}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值