- package cn.istcast.day3;
- import java.lang.reflect.Constructor;
- import java.lang.reflect.InvocationHandler;
- import java.lang.reflect.Method;
- import java.lang.reflect.Proxy;
- import java.util.ArrayList;
- import java.util.Collection;
- public class ProxyTest {
- /**
- * @param args
- */
- public static void main(String[] args) throws Exception{
- Collection proxy3 = (Collection)Proxy.newProxyInstance(Collection.class.getClassLoader(),
- new Class[] {Collection.class},
- new InvocationHandler(){
- ArrayList target = new ArrayList();
- public Object invoke(Object proxy, Method method,
- Object[] args) throws Throwable {
- long beginTime = System.currentTimeMillis();
- Object retVal = method.invoke(target, args);
- long endTime = System.currentTimeMillis();
- System.out.println(method.getName()+"running time of " + (endTime - beginTime));//这里只打印一次,为什么addrunning time of 出现三次,是因为proxy3.add三次吗?这是怎么调用的,哪位能指点一下,谢谢啦!
- return retVal;
- }
- }
- );
- proxy3.add("zxx");
- proxy3.add("lhm");
- proxy3.add("bxd");
- System.out.println(proxy3.size());
- }
- }
- 打印结果:
- addrunning time of 0
- addrunning time of 0
- addrunning time of 0
- sizerunning time of 1
- 3
复制代码 |
|