当前位置:编程学习 > JAVA >>

动态代理

public class MyInvocationHandler implements InvocationHandler {

private Object obj;

public MyInvocationHandler(Object obj) {
super();
this.obj = obj;
}

@Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
long start=System.nanoTime();
System.out.println("开始。。。");
Object result=method.invoke(obj, args);
System.out.println("结束。。。");
long end=System.nanoTime();
System.out.println("干活时间:"+(end-start));
return result;
}

}




public class ProxyFactory {

public static Object getProxy(Object obj){
return Proxy.newProxyInstance(obj.getClass().getClassLoader(), obj.getClass().getInterfaces(), new MyInvocationHandler(obj));
}
}

public class A {
public static void main(String[] args) throws NoSuchMethodException, SecurityException, Throwable{
A a = new A();
Object proxy = ProxyFactory.getProxy(a);
MyInvocationHandler handler=new MyInvocationHandler(a);
handler.invoke(proxy, a.getClass().getMethod("fun", null), null);
String str1="abc";
String str2="abc";
System.out.println("----->"+str1==str2);
}

public void fun(){

System.out.print("H" + "a"); 
System.out.print('H' + 'a'); 

}
}


--------------------编程问答-------------------- any question?
补充:Java ,  Java相关
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,