本帖最后由 夏晓彤 于 2013-3-9 14:37 编辑
下面是张老师动态代理里面的代码,我的理解和问题都在后面注释了,请各位帮帮忙看下
public class ProxyTest {
public static void main(String[] args) {
Collection proxy1 = (Collection)Proxy.newProxyInstance(Collection.class.getClassLoader(),
new Class[]{Collection.class} ,
new InvocationHandler(){
ArrayList trage = new ArrayList();
//执行proxy1.add("xxt1");这里的Object proxy就是proxy1,method是add,args是“xxt1”
public Object invoke(Object proxy, Method method,
Object[] args) throws Throwable {
// TODO Auto-generated method stub
long beginTime = System.currentTimeMillis();
Object recval=method.invoke(trage, args); //目标类对象调用add("xxt1")方法
long endTime = System.currentTimeMillis();
System.out.println(method.getName() + " running time of " + (endTime-beginTime));
System.out.println(recval); //这里为什么打赢的是true???
return recval;
}
}
);
proxy1.add("xxt1");
proxy1.add("xxt2");
proxy1.add("xxt3");
System.out.println(proxy1); //这一句为什么输出的是toString running time of 0 [xxt1, xxt2, xxt3]???
System.out.println(proxy1.size()); //也是先输出size running time of 0???
Class clazz = Proxy.getProxyClass(Collection.class.getClassLoader(), Collection.class);
System.out.println(clazz.getName());
}
} |
|