from: http://kidult.iteye.com/blog/148982
[實戰]java回調函數
關鍵字: 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()方法就可以實現回調功能