先看代码- public class Test01 {
- @SuppressWarnings("unchecked")
- private static <T> Collection<T> newProxyArrayList() {
- //返回代理实例。
- return (Collection<T>)Proxy.newProxyInstance(
- Collection.class.getClassLoader(),
- new Class[] {Collection.class},
- new InvocationHandler() {
- private Collection<T> arrayList = new ArrayList<T>();
- public Object invoke(Object proxy, Method method, Object[] args) {
- long start = System.nanoTime();
- Object retVal = null;
- try {
- retVal = method.invoke(arrayList, args);
- } catch (IllegalArgumentException e) {
- e.printStackTrace();
- } catch (IllegalAccessException e) {
- e.printStackTrace();
- } catch (InvocationTargetException e) {
- e.printStackTrace();
- }
- long end = System.nanoTime();
- System.out.println(method.getName()+"()执行时长:"+(end-start)+"纳秒");
- return retVal;
- }
- });
- }
-
- /**
- * 代理实例测试
- */
- public static void main(String[] args) {
- Collection<String> ProxyArrayList = newProxyArrayList();
- <FONT color=red>ProxyArrayList.add("a");
- ProxyArrayList.add("b");
- ProxyArrayList.add("c");
- </FONT> System.out.println(ProxyArrayList);
- }
- }
- /*
- <FONT color=gray>运行结果:
- add()执行时长:139953纳秒
- add()执行时长:3732纳秒
- add()执行时长:2799纳秒
- toString()执行时长:31101纳秒
- [a, b, c]</FONT>
- */
复制代码 问题是,为什么代理在第一次执行add()时间那么长?
|