问题:写一个ArrayList类的代理,实现和ArrayList中完全相同的功能,并可以计算每个方法运行的时间
------解决方案--------------------
http://www.ticmy.com/?p=200
看第六点
------解决方案--------------------
- Java code
import java.lang.reflect.InvocationHandler;import java.lang.reflect.Method;import java.lang.reflect.Proxy;import java.util.ArrayList;import java.util.List;public class ListProxy { public static void main(String[] args) throws Exception { List<String> list = newList(String.class); list.add("abc"); System.out.println(list); } @SuppressWarnings("unchecked") public static <T> List<T> newList(Class<T> elementType) { return (List<T>)Proxy.newProxyInstance(List.class.getClassLoader(), new Class[]{List.class}, new InvocationHandler() { private List<T> realList = new ArrayList<T>(); public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { long start = System.nanoTime(); Object ret = method.invoke(realList, args); long end = System.nanoTime(); System.out.println("调用" + method.getName() + "耗时:" + (end - start) + "纳秒"); return ret; } }); }}