Java callback function

Source: Internet
Author: User

callback function

My understanding of the callback function

Assume:

My car is at home, now it's broken, I call the almighty mechanic, I told him, hey! Brother, help me fix my car! However, the maintenance workers told me that there is no free time, and so I can come home service! I told the repairman that if you were free, you would come straight to my house and fix it for me.

In the case of a program:

If I want a class that calls my own method of declaring, then I need a callback interface to get my own class to implement it. By doing so, the callback function is implemented. The callback function is like a delegate in C #. There is no similar mechanism in Java. The interface can be used to implement callbacks.

Here is a small demo:

The following is a simple class that contains a callback method that I want to implement, which implements the callback interface for iworkable.

1  Public classCaller implements iworkable{2     /*3 * This is the way I want to be recalled *4      * */5 @Override6      Public voidWork () {7         8System. out. println ("I am the call class method, I succeeded to make calls, I succeeded to let the worker invoke!");9     }Ten  One}

Here is the callback interface:

1  Public Interface iworkable {2     // It 's simply a simple way of defining 3     void Work (); 4 }

Here is the class for the callback operation:

1  Public classWorker {2     3     //The callback interface object, which is assigned to the variable by caller by the Richter conversion law, is passed through this variable to complete the callback operation4 iworkable workable;5     6     /*7 * Assign a value to the corresponding callback function8      * */9      Public  voidsetworkable (iworkable IWA) {Ten          This. workable=IWA; One     } A      -      Public voidWork () { - workable.work (); the     } -}

Summarize:

  The implementation of the callback function actually uses a simple dynamic proxy pattern that executes when it wants to execute.

Java callback function

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.