In Windows, programmers want the system DLL to call a method they have compiled, so they use the callback function (callback) interface in the DLL to compile the program and call it. This is called callback. When calling an interface, you must strictly follow the defined parameters and methods and process the asynchronous function. Otherwise, the program will crash. This explanation seems to be quite difficult. Here is a simple example. 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. . In C/C ++, to use a callback function, the called function must tell the caller its own pointer address, but there is no pointer in Java. What should I do? We can use interfaces to define callback functions.
Suppose I am a programmer, and the following is my program:
Public class caller {private mycallinterface MC; Public Caller () {} public void setmycallinterface (mycallinterface MC) {This. MC = MC;} public void call () {MC. FUC ();} // caller call method}
You need to define an interface so that programmer B can compile the program implementation interface according to my definition.
public interface MyCallInterface {public void fuc();}
As a result, programmer B only needs to implement this interface to achieve the purpose of callback:
Public class callee implements mycallinterface {@ overridepublic void FUC () {system. Out. println ("I have been called by caller! ");}}
The following is the call process:
public class Callbacks {public static void main(String[] args) {MyCallInterface callee = new Callee();Caller caller = new Caller();caller.setMyCallInterface(callee);caller.call();}}
In the above Code,CallerYescaller,CalleeIs called,CallbacksIndicates the call process.
First, a callee object is generated. The caller object generated using this callee object carries some information (that is, the association with the callee object ), therefore, the caller object can use its own call method to call the callee method. -- This is the entire callback process.
If B generates a, a has the ability to call B's method. It is critical to reference interfaces in caller. The callee implemented by this interface only needs to pass its reference to caller.
Generally, you can perform the following steps:
- Declare the unified interface a of the callback function, including the method FUC ();
- Set this interface to private member private a XXX within the call class caller;
- Provide a public method in caller to pass the external "reference of implementation class of this interface a" to XXX through the form parameter;
- The xxx. FUC () method is used in a call () method of caller;
- In the caller instance, pass the object that implements the interface to caller, and then call the call () method.
Source of this article.