Java implements callback functions through anonymous classes

Source: Internet
Author: User

In the C language, a function name can be passed to a parameter as a function pointer to implement a callback

void F1 () {printf ("F1 () \ n");} void F2 () {printf ("f2 () \ n");} void F3 () {printf ("f3 () \ n");} void do_func (void(*f) ()) {f ();} int Main () {    do_func (F1);    Do_func (F2);    Do_func (F3);}

In c++11, implementing callbacks can also be done through function templates and lambda expressions

Template <typename func>void  Do_func (Func f) {f ();} int Main () {    do_func ([] () {printf ("F1 ()");});    Do_func ([] () {printf ("F2 ()");});    Do_func ([] () {printf ("f3 ()");});

And if the code implementation of the callback function is more complex, and has the reuse value, the lambda expression of this one-time scheme is not very suitable, before c++11, by the function object to achieve. The function object is simply a generic object of a class, except that C + + can overload the parentheses operator, causing the operator () method of the object calling the class to be as natural as calling the function.

In essence, the callback function is a specification of a function signature (several input parameters, an output parameter), although there is no function declaration in Java, but Java can use interfaces to enforce the specification.

Interface funcable {    void  Func ();}

So as long as the class of the interface is implemented, there is a function signature and a consistent member function of void Func (well, it is not customary to call the method), so you simply pass the object of the class that implements the interface into the function, and then invoke the Func () method of the object in the function to

classF1Implementsfuncable {@Override Public voidFunc () {System.out.println ("F1 ()"); }    } Public classTest { Public Static voidDo_func (funcable funcable) {funcable.    Func (); }         Public Static voidMain (string[] args) {Do_func (NewF1 ()); }}

Here to save the amount of code, do not put the class F2, F3 to write out. and using anonymous classes in Java can save code, similar to lambda expressions

        Do_func (new  funcable () {                        @Override            publicvoid  func () {                System.out.println ("F2 ()");            }        );

When it comes to lambda expressions, it is possible to capture external variables, and in Java it is possible to explicitly capture external variables through anonymous constructors within anonymous

        String msg = "F3 ()";        Do_func (new  funcable () {            String _msg;                        {                = msg;            }                        @Override            publicvoid  Func () {                System.out.println (_msg);            }        });

This is much like a lambda expression, because the anonymous constructor of an anonymous class can only be constructed with an external variable, which is equivalent to a "capture" of a lambda expression, and a lambda expression corresponding to C + + is

    std::string"f3 ()";    Do_func ([&msg] () {std::cout << msg << Std::endl;});

JAVA8 also has lambda expressions, so it can be written like this

Do_func ((), {System.  out. println (msg); });

Java implements callback functions through anonymous classes

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.