Java callback function

Source: Internet
Author: User
Tags function prototype

Definition on Wikipedia: In computer programming, a callback function, or callback, refers to a piece of executable code that passes through a function parameter to another code. This design allows the underlying code to invoke subroutines defined at the top level.

The so-called callback is that the client program C calls a function A in the service program s, and then s at some point in turn calls a function B in C, for C, the B is called a callback function. Generally speaking, C does not call B,c itself to provide B's purpose is to let s to invoke it, and C has to provide. Since s does not know B name provided by C, S will contract B's interface specification (function prototype), and then by C advance through S's a function R tells S itself to use the B function, this process is called the callback function registration, R is called the registration function. Both the Web service and the Java RMI use a callback mechanism to access the remote server program. Callback more applications are combined with asynchrony.

Here is a popular example: one day, I call you to ask questions, you can not think of a solution, I can't hold the phone in there silly wait, so we agreed: Wait until you come up with a way to call me, so I hung off the phone to do other things. After xx minutes, my cell phone rang, you cheerfully said that the problem has been taken care of, should be treated as such. The story ends here. This example illustrates the programming pattern of asynchronous + callback. Which, you later on the phone to tell me the result is a "callback" process; my mobile phone number must be told you before, this is the registration callback function, my mobile phone number should be valid and the phone can receive your call, this is the callback function must conform to the interface specification.

The following is a sample of two.

Example 1:

1. First define a class caller, according to the above definition is programmer a written by program A, this class to save an interface reference.

1  Public classCaller {2     PrivateMycallinterface Callinterface; 3       4      PublicCaller () {5     }  6       7      Public voidSetcallfunc (Mycallinterface callinterface) {8          This. Callinterface =Callinterface; 9     }  Ten        One      Public voidCall () { A Callinterface.printname ();  -     }   -}

2. Of course, the definition of the interface is required, in order to facilitate programmer B to write a program based on my definition interface.

1  Public Interface mycallinterface {  2public     void  printname ();   3 }  

3. The third is the definition of programmer b written by program B

1  Public class Implements mycallinterface {  2   3    @Override  4      publicvoid  printname () {  5-         System.out.println ("This is the client Printname method ");   6     }  7 }  

4. Test the following

 1  public  class   Test { 2   static  void   main (string[] args) { 3  Caller Caller = new   Caller ();  4  caller.setcallfunc (new   Client ());   5   Caller.call ();  6  }  } 

See here should understand what is callback, some articles introduced very good, but at first did not understand, is because the 3rd step of the class omitted, directly written anonymous class.

5. Use anonymous classes directly in the test method, eliminating the 3rd step.

1  Public classTest {2      Public Static voidMain (string[] args) {3Caller Caller =NewCaller (); 4 //Caller.setcallfunc (New Client ()); 5Caller.setcallfunc (NewMycallinterface () {6              Public voidPrintname () {7System.out.println ("This is the client Printname method"); 8             }  9         }); Ten Caller.call ();  One     }   A}

Example 2:

If we were to test the execution time of a method of a class, we would typically do this:

1  Public   classTestobject {2     /**  3 * A method to be tested for a more time-consuming cycle4      */   5      Public   Static   voidTestMethod () {6          for(inti= 0; i< 100000000; i++){  7               8         }  9     }  Ten     /**   One * A simple way to test the execution time of a method A      */    -      Public   voidTesttime () { -         LongBegin = System.currenttimemillis ();//Test Start Time theTestMethod ();//test Method -         LongEnd = System.currenttimemillis ();//Test End Time -System.out.println ("[Use time]:" + (End-begin));//Print usage Time -     }   +        -      Public   Static   voidMain (string[] args) { +Testobject test=NewTestobject ();  A Test.testtime ();  at     }   -}

You see the Testtime () method, only "//test method" is needed to change, let's do a function to achieve the same function but more flexible:

First, set a callback interface:

1  Public   Interface   CallBack {  2     // method   3 void to perform callback operation          execute ();   4 }  

Then write a tool class:

1  Public   classTools {2       3     /**  4 * Test function usage time, by defining the Execute method of the callback interface5      * @paramCallBack6      */   7      Public   voidtesttime (CallBack CallBack) {8         LongBegin = System.currenttimemillis ();//Test Start Time9Callback.execute ();///Perform callback operationsTen         LongEnd = System.currenttimemillis ();//Test End Time OneSystem.out.println ("[Use time]:" + (End-begin));//Print usage Time A     }   -        -      Public   Static   voidMain (string[] args) { theTools tool =NewTools ();  -Tool.testtime (NewCallBack () { -             //defining the Execute method -              Public   voidExecute () { +                 //Here you can add one or more methods to test the run-time - Testobject.testmethod ();  +             }   A         });  at     }   -        -}

Testtime () passing in the Execute () method that defines the callback interface can implement callback functionality

Reference: http://kidult.iteye.com/blog/148982

http://blog.csdn.net/allen_zhao_2012/article/details/8056665

http://blog.csdn.net/fengyifei11228/article/details/5729445

Java callback function

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.