日期:2014-05-19 浏览次数:20853 次
package blog.dynamicProxy;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
public class JDynamicProxy {
    public static void main(String[] args) {
        RealSubject real=new RealSubject();
        Subject sub=(Subject)java.lang.reflect.Proxy.newProxyInstance(Subject.class.getClassLoader(), new Class[]{Subject.class}, new DynamicProxy(real));
        sub.performance(10000);
        sub.performance(90000);
    }
}
interface Subject{
    public void performance(int n);
}
class RealSubject implements Subject{
    @Override
    public void performance(int n) {
        String str=null;
        for(int i=0;i<n;++i){
            str+=String.valueOf(i);
        }
    }
}
class DynamicProxy implements InvocationHandler{
    protected Object proxied;
    public DynamicProxy(Object o){
        this.proxied=o;
    }
    @Override
    public Object invoke(Object proxy, Method method, Object[] args)
            throws Throwable {
        long before=System.currentTimeMillis();
        method.invoke(proxied, args);
        long time=System.currentTimeMillis()-before;
        System.out.println(time);
        return null;
    }
    
}