publicinterfaceFoo {publicvoidtestArrayList();publicvoidtestLinkedList(); } 然后我們創建測試對象實現這個接口
publicclassFooImpl implements Foo {privateList link=newLinkedList();privateList array=newArrayList();publicFooImpl() {for(inti=0;i<10000;i++) { array.add(newInteger(i)); link.add(newInteger(i)); } }publicvoidtestArrayList() {for(inti=0;i<10000;i++) array.get(i); }publicvoidtestLinkedList() {for(inti=0;i<10000;i++) link.get(i); } } 接下來我們要做關鍵的一步,實現InvocationHandler接口
import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.*;publicclassHandler implements InvocationHandler {privateObject obj;publicHandler(Object obj) {this.obj=obj; }publicstaticObject newInstance(Object obj) { Object result=Proxy.newProxyInstance(obj.getClass().getClassLoader(),
obj.getClass().getInterfaces(),newHandler(obj));return(result); }publicObject invoke(Object proxy, Method method, Object[] args) throws Throwable { Object result;try{ System.out.print("begin method"+method.getName()+"(");for(inti=0; args!=null&&i<args.length; i++) {if(i>0) System.out.print(","); System.out.print(""+args[i].toString()); } System.out.println(")");longstart=System.currentTimeMillis(); result=method.invoke(obj, args);longend=System.currentTimeMillis(); System.out.println("the method"+method.getName()+"lasts"+(end-start)+"ms"); }catch(InvocationTargetException e) {throwe.getTargetException(); }catch(Exception e) {thrownewRuntimeException("unexpected invocation exception:"+e.getMessage()); }finally{ System.out.println("end method"+method.getName()); }returnresult; } } 最后,我們創建測試客戶端,
publicclassTestProxy {publicstaticvoidmain(String[] args) {try{ Foo foo=(Foo) Handler.newInstance(newFooImpl()); 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 使用動態代理的好處是你不必修改原有代碼FooImpl,但是一個缺點是你不得不寫一個接口,如果你的類原來沒有實現接口的話。4.3擴展
在上面的例子中演示了利用動態代理比較兩個方法的執行時間,有時候通過一次簡單的測試進行比較是片面的,因此可以進行多次執行測試對象,從而計算出最差、最好和平均性能。這樣,我們才能“加快經常執行的程序的速度,盡量少調用速度慢的程序”。
延伸閱讀
文章來源于領測軟件測試網 http://www.kjueaiud.com/