---
title: "[实战]java回调函数"
author: "kidult"
date: "2007-12-17T21:41:28Z"
tags: []
slug: "java"
draft: false
lastmod: "2009-08-09T14:12:17Z"
id: 148982
url: "https://kidult.iteye.com/blog/148982"
---

##### 下面使用java回调函数来实现一个测试函数运行时间的工具类：

如果我们要测试一个类的方法的执行时间，通常我们会这样做：

java 代码

 

01. public   class  TestObject {
02. /\**
03. * 一个用来被测试的方法，进行了一个比较耗时的循环
04. \*/
05. public   static   void  testMethod(){
06. for ( int  i= 0 ; i&lt; 100000000 ; i++){
07. }
08. }
09. /\**
10. * 一个简单的测试方法执行时间的方法
11. \*/
12. public   void  testTime(){
13. long  begin = System.currentTimeMillis(); //测试起始时间
14. testMethod(); //测试方法
15. long  end = System.currentTimeMillis(); //测试结束时间
16. System.out.println("\[use time]:"  + (end - begin)); //打印使用时间
17. }
18. public   static   void  main(String\[] args) {
19. TestObject test=new  TestObject();
20. test.testTime();
21. }
22. }

大家看到了testTime()方法，就只有"//测试方法"是需要改变的，下面我们来做一个函数实现相同功能但更灵活：

首先定一个回调接口：

java 代码

 

1. public   interface  CallBack {
2. //执行回调操作的方法
3. void  execute();
4. }

然后再写一个工具类：

java 代码

 

01. public   class  Tools {
02. /\**
03. * 测试函数使用时间，通过定义CallBack接口的execute方法
04. * @param callBack
05. \*/
06. public   void  testTime(CallBack callBack) {
07. long  begin = System.currentTimeMillis(); //测试起始时间
08. callBack.execute(); ///进行回调操作
09. long  end = System.currentTimeMillis(); //测试结束时间
10. System.out.println("\[use time]:"  + (end - begin)); //打印使用时间
11. }
12. public   static   void  main(String\[] args) {
13. Tools tool = new  Tools();
14. tool.testTime(new  CallBack(){
15. //定义execute方法
16. public   void  execute(){
17. //这里可以加放一个或多个要测试运行时间的方法
18. TestObject.testMethod();
19. }
20. });
21. }
22. }

大家看到，testTime()传入定义callback接口的execute()方法就可以实现回调功能