Aop动态代理

package com.aop.proxy;

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

public class ProxyProvider {

	private MathCaculate target;

	public ProxyProvider(MathCaculate target) {
		super();
		this.target = target;
	}

	public MathCaculate getProxy() {
		
		ClassLoader loader = target.getClass().getClassLoader();
		
		Class<?>[] interfaces = target.getClass().getInterfaces();
		
		 InvocationHandler h = new InvocationHandler() {

			@Override
			public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
				
				Object result = null;
				String methodname = method.getName();
				
				try {
					
					
					System.out.println("[日志][方法名:"+methodname+"[方法开始]参数:"+Arrays.asList(args)+"]");
					
			
				
					result  =	method.invoke(target, args);
					System.out.println("[日志][方法名:"+methodname+"[方法正常结束][参数:"+result+"]");
				} catch (Exception e) {
					
					e.printStackTrace();
					System.out.println("[日志][方法名:"+methodname+"[方法异常][参数:"+e.getClass().getName()+"]");
				}finally {
					System.out.println("[日志][方法名:"+methodname+"[方法结束]");
				}
				
				return result;
			}
			 
		
		};	 
		 
		
		
		MathCaculate proxy = (MathCaculate) Proxy.newProxyInstance(loader, interfaces, h);
		
		return proxy;
		
	}
}

其他代码在上一篇

package com.aop.proxy;

public class MathCaculateTest {

	public static void main(String[] args) {

		MathCaculate caculator = new success();
		
		//MathCaculate caculator = new Log();
		caculator.add(5, 5);
		System.out.println();
		caculator.sub(5, 5);
		System.out.println();
		caculator.mul(5, 5);
		System.out.println();
		caculator.div(5, 5);
		System.out.println();
		
		ProxyProvider provider = new ProxyProvider(caculator);
		caculator = provider.getProxy();
		
		caculator.add(5, 5);
		System.out.println();
		caculator.sub(5, 5);
		System.out.println();
		caculator.mul(5, 5);
		System.out.println();
		caculator.div(5, 0);
		System.out.println();
		
		
	}

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值