简单的理解代理就是为一个类生成一个代理对象,而这个对象对原类中方法执行前后加上了一些操作。
我们先看一下产生代理的实例:
package com.yc.spring.demo.impl;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Arrays;
import com.yc.spring.demo.ArithmeticCalculator;
import com.yc.spring.util.LoggerUtil;
//动态代理,, 切面中可包括,前切,后切,目标,通知 目标就是传过来的arithmeticCalculator,包括多个切点(具体的某一个方法)
public class ArithmeticCalculatorProxy {
//代理 arithmeticCalculator是目标
public static ArithmeticCalculator getInstance(final ArithmeticCalculator arithmeticCalculator){
//找到加载器的位置, 例如工厂要知道它生产的物品是什么,要找到有关它的信息 ,类是抽象的,对象是具体的
ClassLoader loader=arithmeticCalculator.getClass().getClassLoader();
//类(目标)有哪些要处理的方法 , 例如工厂要知道这个物品所有的功能,
Class[] interfaces=arithmeticCalculator.getClass().getInterfaces();
//绑定要处理的方法
//InvocationHandler是一个接口不能new,
InvocationHandler h=new InvocationHandler() {
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
//Arrays.asList(args)将数组args转List集合
//通知
LoggerUtil.log.debug("the method "+method.getName()+" begins arguments ["+Arrays.asList(args)+"]");
//获得真正要执行方法的结果
Object result=method.invoke(arithmeticCalculator, args);
//通知
LoggerUtil.log.debug("the "+method.getName()+" end result ["+result+"]");
return result;
}
};
//返回代理对象
return (ArithmeticCalculator) Proxy.newProxyInstance(loader, interfaces, h);
}
}
这样就有了类的代理,当调用原类中的方法时,实际执行的是代理类生成的对象处理过后的方法。
再看一下,代理的应用:
package com.yc.spring.demo;
import com.yc.spring.demo.impl.ArithmeticCalculatorImpl;
import com.yc.spring.demo.impl.ArithmeticCalculatorProxy;
import junit.framework.TestCase;
public class ArithmeticCalculatorImplTest extends TestCase {
private ArithmeticCalculator arithmeticCalculator;
protected void setUp() throws Exception {
//获得动态代理对象
arithmeticCalculator=ArithmeticCalculatorProxy.getInstance(new ArithmeticCalculatorImpl());
}
protected void tearDown() throws Exception {
arithmeticCalculator=null;
}
public void testAdd() {
assertEquals(6,arithmeticCalculator.add(4, 2));
}
public void testMinus() {
assertEquals(2,arithmeticCalculator.minus(4, 2));
}
public void testMultipation() {
assertEquals(8,arithmeticCalculator.multipation(4, 2));
}
public void testDivide() {
assertEquals(2,arithmeticCalculator.divide(4, 2));
}
}
运行结果如下: