Java callback function, java callback function example

Source: Internet
Author: User

Java callback function, java callback function example

The so-called callback is that programmer A writes a program (program A), which reserves the callback function interface and encapsulates the program. Programmer B wants a to call a method in program B, So he calls back the method in B through the interface in.

1. First define A class Caller. According to the above definition, it is program a written by programmer A. This class stores an interface reference.

public class Caller {      private MyCallInterface callInterface;            public Caller() {      }            public void setCallFunc(MyCallInterface callInterface) {          this.callInterface = callInterface;      }            public void call() {          callInterface.printName();      }  }

2. Of course, the interface definition is required. To help programmer B compile the program implementation interface according to my definition.

public interface MyCallInterface {      public void  printName();  }

3. The third is to define the program B written by programmer B.

public class Client implements MyCallInterface {        @Override      public void printName() {          System.out.println("This is the client printName method");      }  }

4. The test is as follows:

public class Test {      public static void main(String[] args) {          Caller caller = new Caller();          caller.setCallFunc(new Client());          caller.call();      }  }

5. Use the Anonymous class directly in the test method, saving step 1.

public class Test {      public static void main(String[] args) {          Caller caller = new Caller();  //      caller.setCallFunc(new Client());          caller.setCallFunc(new MyCallInterface() {              public void printName() {                  System.out.println("This is the client printName method");              }          });          caller.call();      }  }
I am the dividing line of tiantiao

 

 

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


What is the callback function in JAVA? It is best to include an example to describe how to make it easier ,,

For example, if you write two classes A and B, and each generates a corresponding instance a and B, there is A method fa in a (this method is only responsible for generating two random numbers) you need to call a method fb in B (this method calculates each of the two numbers) to sum, after obtaining the result from fb, you need to call another method (ffa) of a (this method is used to display the obtained result). In this case, ffa is called the callback function (which is called back)
Why is it so troublesome? If fb does not return results directly, imagine that if fb takes a long execution time, fa will wait until the results are executed, and fa will not execute any further, in this case, the callback function is implemented using the callback function. Because the callback function is generally called asynchronously by the system, the method fa will directly execute the function after calling fb without waiting. For example, two random numbers can be generated to fb, after obtaining the results in sequence, fb calls the ffa function through the callback mechanism to display the results. In fact, it is used to generate random numbers and calculate random numbers asynchronously. It seems that fa and fb are two independent threads to improve program efficiency.

Java callback function problems?

The following uses the java callback function to implement a tool class for testing the function running time: 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. A time-consuming loop */public static void testMethod () {for (int I = 0; I <100000000; I ++) {}}/*** a simple test method */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 time used} public static void main (String [] args) {TestObject test = new TestObject (); test. testTime () ;}you can see the testTime () method. Only "// test 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 ();} and then write a tool class: java code public class Tools {/*** test 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 (); // perform the callback operation long end = System. currentTimeMillis (); // test end time System. out. println ("[use time]:" + (end-begin); // print the time used} public static void main (String [] args) {Tools tool = new Tools (); tool. testTime (new CallBack () {// defines the execute method public void execute () {// here you can add one or more methods TestObject to test the running time. testMethod () ;}}) ;}you can see that the callback function can be implemented by passing in testTime () to the execute () method that defines the callback interface.

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.