The following uses the Java callback function to implement a tool class for testing the function runtime:
If we want to test the execution time of a class method, we usually do this:
Java code
- Public class testobject {
- /**
- * A method used for testing carries out a time-consuming cycle.
- */
- Public static void testmethod (){
- For (INT I = 0; I <100000000; I ++ ){
- }
- }
- /**
- * A Simple Method for Testing the execution time
- */
- Public void testTime (){
- Long begin = System. currentTimeMillis (); // Test start time
- TestMethod (); // Test Method
- Long end = System. currentTimeMillis (); // test end Time
- System. out. println ("[use time]:" + (end-begin); // print the usage time
- }
- Public static void main (String [] args ){
- TestObject test = new TestObject ();
- Test. testTime ();
- }
- }
As you can see, only the "// test method" of the testtime () method needs to be changed. Let's create a function to implement the same function but be more flexible:
First, define a callback interface:
Java code
- Public interface CallBack {
- // Method for executing the callback operation
- Void execute ();
- }
Then write a tool class:
Java code
- Public class Tools {
- /**
- * Test the function usage time by defining the execute method of the CallBack Interface
- * @ Param callBack
- */
- Public void testTime (CallBack callBack ){
- Long begin = System. currentTimeMillis (); // Test start time
- CallBack.exe cute (); // call back
- Long end = System. currentTimeMillis (); // test end Time
- System. Out. println ("[use time]:" + (end-begin); // print the usage time
- }
- Public static void main (string [] ARGs ){
- Tools tool = new tools ();
- Tool. testtime (New callback (){
- // Define the execute Method
- Public void execute (){
- // Add one or more methods to test the running time.
- TestObject. testMethod ();
- }
- });
- }
- }
As you can see, the callback function can be implemented by passing testtime () to the execute () method that defines the callback interface.
Go to: If you forget it, use it if you think it is useful. Thank you.