下面使用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()方法,就只有"//測試方法"是需要改變的,下面我們來做一個函數實現相同功能但更靈活:
首先定一個回調介面:
java 代碼
- public interface CallBack {
- //執行回調操作的方法
- void execute();
- }
然後再寫一個工具類:
java 代碼
- 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()方法就可以實現回調功能
轉至: 忘記了,覺得有用就拿來了,謝謝了