java回撥函式

handawei_5發表於2010-09-19
下面使用java回撥函式來實現一個測試函式執行時間的工具類:


如果我們要測試一個類的方法的執行時間,通常我們會這樣做:

java 程式碼
public   class  TestObject {   
   /**   
   * 一個用來被測試的方法,進行了一個比較耗時的迴圈   
     */    
    public   static   void  testMethod(){   
       for ( int  i= 0 ; i< 100000000 ; i++){   
              
       }   
   }   
   /**   
    * 一個簡單的測試方法執行時間的方法   
    */    
  public   void  testTime(){   
      long  begin = System.currentTimeMillis(); //測試起始時間    
       testMethod(); //測試方法    
       long  end = System.currentTimeMillis(); //測試結束時間    
   System.out.println("[use time]:"  + (end - begin)); //列印使用時間    
   }   
     
   public   static   void  main(String[] args) {   
      TestObject test=new  TestObject();   
       test.testTime();   
    }   
} 
 大家看到了testTime()方法,就只有"//測試方法"是需要改變的,下面我們來做一個函式實現相同功能但更靈活:

首先定一個回撥介面:
public   interface  CallBack {   
   //執行回撥操作的方法    
   void  execute();   
}   
 
然後再寫一個工具類:
public   class  Tools {   
       
    /**   
     * 測試函式使用時間,通過定義CallBack介面的execute方法   
     * @param callBack   
     */    
    public   void  testTime(CallBack callBack) {   
        long  begin = System.currentTimeMillis(); //測試起始時間    
        callBack.execute(); ///進行回撥操作    
        long  end = System.currentTimeMillis(); //測試結束時間    
        System.out.println("[use time]:"  + (end - begin)); //列印使用時間    
    }   
       
    public   static   void  main(String[] args) {   
        Tools tool = new  Tools();   
        tool.testTime(new  CallBack(){   
            //定義execute方法    
            public   void  execute(){   
                //這裡可以加放一個或多個要測試執行時間的方法    
                TestObject.testMethod();   
            }   
        });   
    }   
       
} 
 大家看到,testTime()傳入定義callback介面的execute()方法就可以實現回撥功能

相關文章