Home > Java > javaTutorial > body text

Example explanation of using anonymous classes to implement callback functions in Java

黄舟
Release: 2017-08-22 10:10:45
Original
1601 people have browsed it

This article mainly introduces examples of Java implementing callback functions through anonymous classes. The callback function is a specification of a function signature (several input parameters, one output parameter). Although there is no function declaration in Java, Java can Use interfaces to enforce specifications. You can check the detailed explanation below for the specific operation steps, and interested friends can refer to it.

In C language, the function name can be passed as a function pointer to the formal parameter to implement 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);
}
Copy after login

In C++11, callback can also be implemented You can use 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()"); });
}
Copy after login

If the code implementation of the callback function is more complex and has reuse value, lambda expressions are a one-time solution. It is not suitable. Before C++11, it was implemented through function objects. To put it bluntly, a function object is an ordinary object of a class, but C++ can overload the bracket operator, so that calling the operator() method of an object of the class is as natural as calling a function.

Analyzing the essence, in fact, the callback function is a specification of a function signature (several input parameters, one output parameter). Although there is no function declaration in Java, Java can use interfaces to enforce specifications.


interface Funcable {
  void Func();
}
Copy after login

In this way, as long as the class that implements the interface has a member function with the same function signature as void Func() (well, I am still not used to the method) method), so you only need to pass the object of the class that implements the interface into the function, and then call the Func() method of the object in the function


class F1 implements Funcable {

  @Override
  public void Func() {
    System.out.println("f1()");
  } 
}
public class Test {
  
  public static void do_func(Funcable funcable) {
    funcable.Func();
  } 
  public static void main(String[] args) {
    do_func(new F1());
  }
}
Copy after login

To save the amount of code here, classes F2 and F3 will not be written. And using Java's anonymous classes can save code, similar to lambda expressions


  do_func(new Funcable() {      
      @Override
      public void Func() {
        System.out.println("f2()");
      }
    });
Copy after login

Speaking of lambda expressions, it can capture external variables, in this way in Java You can also explicitly capture external variables through the anonymous constructor inside the anonymous


  String msg = "f3()";
    do_func(new Funcable() {
      String _msg; 
      {
        _msg = msg;
      } 
      @Override
      public void Func() {
        System.out.println(_msg);
      }
    });
Copy after login

This approach is very similar to a lambda expression, because the anonymous constructor of the anonymous class It can only use external variables as construction parameters, which is equivalent to the "capture" of lambda expressions. The corresponding lambda expression writing method in C++ is


 std::string msg = "f3()";
  do_func([&msg]() { std::cout << msg << std::endl; });
Copy after login

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

do_func(() -> { System.out.println(msg); });
Copy after login

The above is the detailed content of Example explanation of using anonymous classes to implement callback functions in Java. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template