long start=System.currentTimeMillis(); doSth(); long end=System.currentTimeMillis(); System.out.println("time lasts "+(end-start)+"ms");
public interface Foo { public void testArrayList(); public void testLinkedList(); }
public class FooImpl implements Foo { private List link=new LinkedList(); private List array=new ArrayList(); public FooImpl() { for(int i=0;i<10000;i++) { array.add(new Integer(i)); link.add(new Integer(i)); } } public void testArrayList() { for(int i=0;i<10000;i++) array.get(i); } public void testLinkedList() { for(int i=0;i<10000;i++) link.get(i); } }
import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.*; public class Handler implements InvocationHandler { private Object obj; public Handler(Object obj) { this.obj = obj; } public static Object newInstance(Object obj) { Object result = Proxy.newProxyInstance(obj.getClass().getClassLoader(),
obj.getClass().getInterfaces(), new Handler(obj)); return (result); } public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { Object result; try { System.out.print("begin method " + method.getName() + "("); for (int i = 0; args != null && i < args.length; i++) { if (i > 0) System.out.print(","); System.out.print(" " + args[i].toString()); } System.out.println(" )"); long start=System.currentTimeMillis(); result = method.invoke(obj, args); long end=System.currentTimeMillis(); System.out.println("the method "+method.getName()+" lasts "+(end-start)+"ms"); } catch (InvocationTargetException e) { throw e.getTargetException(); } catch (Exception e) { throw new RuntimeException("unexpected invocation exception: " + e.getMessage()); } finally { System.out.println("end method " + method.getName()); } return result; } }
public class TestProxy { public static void main(String[] args) { try { Foo foo = (Foo) Handler.newInstance(new FooImpl()); foo.testArrayList(); foo.testLinkedList(); } catch (Exception e) { e.printStackTrace(); } } }
运行的结果如下:
begin method testArrayList( ) the method testArrayList lasts 0ms end method testArrayList begin method testLinkedList( ) the method testLinkedList lasts 219ms end method testLinkedList