Collection proxy31 = (Collection) Proxy.newProxyInstance(
Constructor.class.getClassLoader(),
new Class[] { Collection.class }, new InvocationHandler() {
ArrayList obj = new ArrayList();
@Override
public Object invoke(Object proxy, Method method,
Object[] args) throws Throwable {
// TODO Auto-generated method stub
long starttime = System.currentTimeMillis();
Object retval = method.invoke(obj, args);
long endtime = System.currentTimeMillis();
System.out.println(method.getName() + " "
+ "the time of running" + ":"
+ (endtime - starttime));
return retval;
}
});
proxy31.add("zhou");
proxy31.add("shao");
proxy31.add("wen");
System.out.println(proxy31.size());
运行结果:
add the time of running:0
add the time of running:0
add the time of running:0
size the time of running:0
3
此时ArrayList obj = new ArrayList();在invoke()外面,obj是作为一个成员变量,所以add() 和size()操作的是同一个。当语句放到invoke()里面的时候,add()调用一次invoke()都是操作一个新的obj。这样size()得到的结果为0 |