动态代理,作为实现AOP的方式之一,已经得到广泛的应用.本人看了很多书关于动态代理的介绍,基本就是不知所云. 所以最终自己做了一个例子,才感到有点明白,下面是我的代码package pear;
//import org.springframework.aop.Advisor;
//import org.springframework.aop.BeforeAdvice;
import java.lang.reflect.*;
interface SayInterface{ // 被代理借口
public void say();
public void saytwo();
}
class Say implements SayInterface{ // 被代理的类
public void say(){
System.out.println(" in say ");
}
public void saytwo(){
System.out.println("in say 2");
}
}
class SayHandler implements InvocationHandler{ //
private Say mysay = new Say(); //先生成一个"被代理类"的对象
public Object invoke(Object proxy,Method method,Object[] args)throws Exception{
System.out.println("Before"); //方法调用之前输出Before
method.invoke(mysay,args); //原来方法在这里才真正被调用
//method.invoke(saytwo,args);
System.out.println("After"); //方法调用之后输出After
return null;
}
}
public class Main {
/** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub SayHandler handler = new SayHandler(); SayInterface si = (SayInterface)Proxy.newProxyInstance( SayInterface.class.getClassLoader(),new Class[]{SayInterface.class},handler);/** SayInterface si = (SayInterface)Proxy.newProxyInstance(// handler.getClass().getClassLoader(),handler.say.getClass().getInterfaces(),handler); //被代理接口的类加载器,被加载的类,和。。。。 SayInterface si = (SayInterface)Proxy.newProxyInstance(handler.getClass().getClassLoader(),); */ si.say(); si.saytwo(); System.out.println("the end.........."); }
}//说明同一个包里面的类的类加载器(ClassLoader)是一样的 |