后,我们创建测试客户端,

publicclassTestProxy{

publicstaticvoidmain(String[]args){

try{

Foofoo=(Foo)Handler.newInstance(newFooImpl());

foo.testArrayList();

foo.testLinkedList();

}catch(Exceptione){

e.printStackTrace();

}

}

}

  运行的结果如下:

beginmethodtestArrayList()

themethodtestArrayListlasts0ms

endmethodtestArrayList

beginmethodtestLinkedList()

themethodtestLinkedListlasts219ms

endmethodtestLinkedList

  使用动态代理的好处是你不必修改原有代码FooImpl,但是一个缺点是你不得不写一个接口,如果你的类原来没有实现接口的话。

  4.3扩展

  在上面的例子中演示了利用动态代理比较两个方法的执行时间,有时候通过一次简单的测试进行比较是片面的,因此可以进行多次执行测试对象,从而计算出差、好和平均性能。这样,我们才能“加快经常执行的程序的速度,尽量少调用速度慢的程序”。


  5内存消耗测试

  5.1目标

  当一个java应用程序运行时,有很多需要消耗内存的因素存在,像对象、加载类、线程等。在这里只考虑程序中的对象所消耗的虚拟机堆空间,这样我们可以利用Runtime类的freeMemory()和totalMemory()方法。

  5.2实现

  为了方便期间,我们首先添加一个类计算当前内存消耗。

classMemory

{

publicstaticlongused()

{

longtotal=Runtime.getRuntime().totalMemory();

longfree=Runtime.getRuntime().freeMemory();

return(total-free);

}

}

  然后修改Handler类的invoke()方法。

publicObjectinvoke(Objectproxy,Methodmethod,Object[]args)throwsThrowable{

Objectresult;

try{

System.out.print("beginmethod"+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=Memory.used();

result=method.invoke(obj,args);

longend=Memory.used();

System.out.println("memoryincreasedby"+(end-start)+"bytes");

}catch(InvocationTargetExceptione){

throwe.getTargetException();

}catch(Exceptione){

thrownewRuntimeException

("unexpectedinvocationexception:"+

e.getMessage());

}finally{

System.out.println("endmethod"+method.getName());

}

returnresult;

}