本帖最后由 tshch1989 于 2013-5-21 17:47 编辑
昨天看5月19的试题上有个动态代理的问题,今天研究了下,写了点小代码,但是对代理在实际应用还是理解不深刻,不知道能做点什么,有什么优点?
package reflect;
import java.lang.reflect.*;
public class ProxyDemo {
/**
* @param args
* @throws SecurityException
* @throws NoSuchMethodException
* @throws InvocationTargetException
* @throws IllegalArgumentException
* @throws IllegalAccessException
* @throws InstantiationException
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
MyFoo mf=new MyFoo("zhangsan",22);
MyInvocation handler=new MyInvocation(mf);
Foo f=(Foo)Proxy.newProxyInstance(mf.getClass().getClassLoader(), mf.getClass().getInterfaces(), handler);
System.out.println(f.getClass().getName());//测试参数是否是f
Integer i=f.show();
System.out.println(i);
}
}
//要被代理的接口
interface Foo{
public int show();
}
//实现了代理接口的类,再本例中实现的show()函数将被代理执行
class MyFoo implements Foo{
private String name;
private int age;
MyFoo(String name,int age){
this.name=name;
this.age=age;
}
@Override
public int show() {
// TODO Auto-generated method stub
System.out.println("progress run..."+name+"..."+age);
return 1;
}
}
//实现了InvocationHandler接口,该类的invoke方法将取代被代理类MyFoo中show()方法的直接运行;
class MyInvocation implements InvocationHandler{
private Object obj=null;
MyInvocation(Object obj){
this.obj=obj;
}
@Override
public Object invoke(Object arg0, Method arg1, Object[] arg2)
throws Throwable {
// TODO Auto-generated method stub
System.out.println(arg0.getClass().getName());//测试参数
System.out.println(arg1.getName());//测试参数
System.out.println("before progeress run");
arg1.invoke(obj, arg2);
System.out.println("after progress run");
return 1;//测试返回,跟接口中的返回类型相同或兼容
}
}
|