日期:2014-05-20 浏览次数:20782 次
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; } }); } }