java动态代理的一个小例子

总共四个类,一个接口类、一个接口实现类、一个动态代理类、一个测试类。

接口类:

package com.qw.spring;

public interface AtithmeticCalculator {
	
	int add(int i,int j);
	
	int sub(int i,int j);
}

接口实现类:

package com.qw.spring;

public class AtithmeticCalculatorImpl implements AtithmeticCalculator {

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

}

动态代理类:

package com.qw.spring;

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

public class ArithmeticCalculatorLoggingProxy {
	
	//要代理的对象
	private AtithmeticCalculator target;
	
	public ArithmeticCalculatorLoggingProxy(AtithmeticCalculator target){
		this.target = target;
	}
	
	
	public AtithmeticCalculator getlLoggingProxy(){
		AtithmeticCalculator proxy = null;
		
		//代理对象由哪一个类加载器负责加载
		ClassLoader loader = target.getClass().getClassLoader();
		//代理对象的类型,即其中有哪些方法
		Class[] interfaces = new Class[]{AtithmeticCalculator.class};
		//当调用代理对象其中的方法是,该执行的代码
		InvocationHandler h = new InvocationHandler() {
			/**
			 * proxy:正在返回的那个代理对象,一般情况下,在invoke方法中都不使用该对象。
			 * method:正在被调用的方法
			 * args:调用方法时,传入的参数
			 */
			@Override
			public Object invoke(Object proxy, Method method, Object[] args)
					throws Throwable {
				System.out.println("被调用的方法名:"+method.getName());
				
				//执行的方法
				Object result = method.invoke(target, args);
				
				return result;
			}
		};
		
		proxy = (AtithmeticCalculator) Proxy.newProxyInstance(loader, interfaces, h);
		
		return proxy;
	}
}

测试类:

package com.qw.spring;

public class Main {
	public static void main(String[] args) {
		AtithmeticCalculator target = new AtithmeticCalculatorImpl();
		AtithmeticCalculator proxy = new ArithmeticCalculatorLoggingProxy(target).getlLoggingProxy();
		
		int result = proxy.add(1, 2);
		System.out.println(result);
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值