Java callback functions in a detailed

Source: Internet
Author: User
Tags function prototype

To understand what a callback function is, check the following information online:

Information One:

First of all, what is called a callback function?

In Windows, the programmer wants the system DLL to call a method written by itself, and then uses the interface of the callback function (CALLBACK) in the DLL to write the program, which is called the callback. When you invoke an interface, you need to strictly follow the defined parameters and method calls, and you need to handle the async of the function, which will cause the program to crash.

This explanation seems to be quite difficult to understand, here is a simple example:

Programmer a wrote a program (program a), which reserved a callback function interface, and encapsulated the program. Programmer B wants A to invoke a method in its own program B, so he callbacks his method in B through the interface in a. Objective to achieve.

In C + +, to use a callback function, the dropped function needs to tell the caller their own pointer address, but there is no pointer in Java, what to do? We can implement the definition callback function through the interface (interface).

Let's say I'm programmer a, and here's my program A:

[Java]View Plaincopyprint?
  1. Public class Caller {
  2. Public Mycallinterface MC;
  3. Public void Setcallfuc (Mycallinterface MC) {
  4. this.mc= MC;
  5. }
  6. Public Void Call () {
  7. This.mc.method ();
  8. }
  9. }

I also need to define an interface so that programmer B implements the interface based on my definition of programming.

[Java]View Plaincopyprint?
    1. Public interface Mycallinterface {
    2. Public void Method ();
    3. }

So, programmer B only needs to implement this interface to achieve the purpose of the callback:

[Java]View Plaincopyprint?
  1. Public class B implements Mycallinterface {
  2. Public Void Method () {
  3. System.out.println ("Who will call me ah.") So lonely!!   ");
  4. }
  5. Public static void Main (String args[]) {
  6. Caller call = new Caller ();
  7. CALL.SETCALLFUC (new B ());
  8. Call.call ();
  9. }
  10. }
public class B implements Mycallinterface {public void method () {System.out.println ("Who will call me ah.") So lonely!! "); } public static void Main (String args[]) {Caller call = new Caller (); Call.setcallfuc (new B ()); Call.call ();}}

Data two:

The so-called callback, is the client program C calls the service program s in a method A, and then s at some point in turn to call a C method B, 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 what B is called by C, so S will contract B's interface specification (function prototype), and then by C advance through S a function R tells S itself will use B function, this process is called callback function registration, R is called the registration function.

Here's a popular example:

One day, I call to ask you questions, of course, is a problem,:), you can not think of a solution, I can't hold the phone in there silly, 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.

If you're not sure how to look at this section of the description code:

Declare an interface, another class has a method that has a parameter to be the interface type, and then implement this interface in another class (in Java is used in the anonymous inner class), and the object generated by the anonymous class for the parameter to the above mentioned class, and then implement the callback .... This usage can be referred to in Java common to the database operations used by several interfaces .....

[Java]View Plaincopyprint?
  1. Declaring an interface
  2. Public interface Icallback {
  3. void Postexec ();
  4. }
  5. Another class has a method that has a parameter in it that is the interface type
  6. Public class FooBar {
  7. Private Icallback CallBack;
  8. Public void Setcallback (Icallback callBack) {
  9. This.callback = CallBack;
  10. }
  11. Public void Dosth () {
  12. Callback.postexec ();
  13. }
  14. }
  15. ----------------------------------------
  16. Implementation of callbacks
  17. Public class Test {
  18. Public static void Main (string[] args) {
  19. FooBar foo = new FooBar ();
  20. Foo.setcallback (new Icallback () {
  21. Public void Postexec () {
  22. System.out.println ("method executed.");
  23. }
  24. });
  25. Foo.dosth (); //Call function
  26. }
  27. }
Declares an interface public interface Icallback {void Postexec ();} Another class has a method that has a parameter in it that is the public class of this interface type FooBar {private icallback callback;public void Setcallback (Icallback callBack) { This.callback = CallBack;} public void Dosth () {callback.postexec ();}} Implementation of the----------------------------------------callback public class Test {public static void main (string[] args) {FooBar foo = new F Oobar (); Foo.setcallback (new Icallback () {public void postexec () {System.out.println ("method executed.");}); Foo.dosth ();//Call Function}}

--------------------------------------------------------------------------------------------------------------- ---------------------------------------------

Data three: A classic example of using a callback function

The following is a tool class that uses the Java callback function to implement a test function run time:

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

Java code

[Java]View Plaincopyprint?
  1. Public class Testobject {
  2. /**
  3. * A method to be tested for a more time-consuming cycle
  4. */
  5. Public static void TestMethod () {
  6. for ( int i= 0; i< 100000000; i++) {
  7. }
  8. }
  9. /**
  10. * A simple way to test the execution time of a method
  11. */
  12. Public void Testtime () {
  13. Long begin = System.currenttimemillis (); //Test start time
  14. TestMethod (); //test method
  15. Long end = System.currenttimemillis (); //test End time
  16. System.out.println ("[Use time]:" + (End-begin)); //Print usage time
  17. }
  18. Public static void Main (string[] args) {
  19. Testobject test=New Testobject ();
  20. Test.testtime ();
  21. }
  22. }

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:

Java code

[Java]View Plaincopyprint?
  1. Public interface CallBack {
  2. Methods for performing callback operations
  3. void execute ();
  4. }
  5. Then write a tool class:
  6. Java code
  7. Public class Tools {
  8. /**
  9. * Test function usage time, by defining the Execute method of the callback interface
  10. * @param callBack
  11. */
  12. Public void Testtime (CallBack CallBack) {
  13. Long begin = System.currenttimemillis (); //Test start time
  14. Callback.execute (); // for callback operation
  15. Long end = System.currenttimemillis (); //test End time
  16. System.out.println ("[Use time]:" + (End-begin)); //Print usage time
  17. }
  18. Public static void Main (string[] args) {
  19. Tools tool = new tools ();
  20. Tool.testtime (new CallBack () {
  21. Defining the Execute Method
  22. Public Void Execute () {
  23. Here you can add one or more methods to test the run-time
  24. Testobject.testmethod ();
  25. }
  26. });
  27. }
  28. }

As you can see, testtime () passed the Execute () method that defines the callback interface to implement the callback function

Java callback functions in a detailed

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.