Home  >  Article  >  Java  >  Let’s talk about java callback function again

Let’s talk about java callback function again

高洛峰
高洛峰Original
2017-01-24 13:41:191027browse

I encountered the callback function again, this time I plan to write it down and share it.

The so-called callback function, or callback method in object-oriented language, to put it simply, is a function that is called back at a certain time (event occurs).

To be more detailed: it is a function A, as a parameter, passed in another function B, and then called by B at a certain time.

You may have questions here. Since one function calls another function, it can be called in the function body. Why do you need to pass the function as a parameter to another function to be called? Not to mention that there are some languages ​​​​(such as java) does not support functions as parameters.

Yes, you can indeed call another function in the function body. There seems to be no difference in function, but there is a problem here, that is, the function you want to call is hard-coded, which means this Function B can only call function A, so what if in another scenario, there is a function C that is different from A and needs to be called at a certain moment in B.

Let’s continue talking about the callback function. In c/c++, the callback function can be called by another function using a function pointer as a parameter; in c#, you can use a delegate. If it is an event method, there is an event key. In python and javascript, you can directly pass functions as object parameters. These languages ​​​​are easy to implement callback functions (methods), but what about java? Let me digress first. Ever since I learned C#, I don’t like java. I once planned to stop using Java in the future, but the reality is not that ideal. Now I want to make Android, so I still can't let go of Java. And today I encountered the problem of this callback function, which I also encountered from Java. I personally think, The languages ​​that appear in this blog, except Java, can all implement callbacks easily and understandably. However, I don’t think that is the case with Java, otherwise I would not be writing this blog.

Okay, let’s continue talking about the implementation of callback methods in java. The focus of this blog is about java. In Java, callback methods are implemented by borrowing interfaces. I found a sentence on the Internet:

"Assign the reference of the object created by the class that implements a certain interface to the interface variable declared by the interface. , then the interface variable can call the method of the implemented interface."
It’s very confusing, let’s explain briefly:
There is an interface, and there is a method in the interface (this method is the method to be called back):

interface CallBackInterface {
  void callBackMethod();
}

We know that interface The object cannot be used directly because none of the methods inside it are implemented. So find a class to implement this interface.
So now add a class to implement this interface:

interface CallBackInterface {
  void callBackMethod();
}
 
class CallBackClass implements CallBackInterface{
 
  @Override
  public void callBackMethod() {
    System.out.println("hello");
  }
}

Okay, the last step: assign the object of the class that implements the interface to the declared Interface variable (I wrote it into a method, and then added a class shell outside):

public class CallBackTest {
 
  interface CallBackInterface {
    void callBackMethod();
  }
 
  class CallBackClass implements CallBackInterface {
 
    @Override
    public void callBackMethod() {
      System.out.println("hello");
    }
  }
 
  public void showCallBack() {
    CallBackInterface itfs = new CallBackClass();
    itfs.callBackMethod();
  }
}

Now you can call it and try it:

public class Test {
  public static void main(String[] args) {
    new CallBackTest().showCallBack();
  }
}

If there are no accidents, hello will be output successfully. Anyway, it is on my side.

I have finished reading the example, so what did I do? Let me explain in more detail. , we have a method to be called in a certain method (this method is the callback method). As we said before, it is best not to directly write what you want the callback method to do directly in the calling method, and because java There is no way to pass the method as a parameter, so we have to put the callback method in the interface (why not a class? Not an abstract class? But an interface? You can find the similarities and differences between abstract classes and interfaces and solve this yourself. question). If there is an interface, it must be implemented by the class. Then, as long as the object of the interface is assigned an object of the implementing class, the object of this interface can call that method. To understand this, one important point is polymorphism. The polymorphic knowledge used here is that the object of the interface can be successfully assigned by a subclass, and the overridden method of the subclass can be called (classes also have similar concepts).

To say one more thing, any class here that implements the CallbackInterface interface can be placed after new as follows (that is, assignment):

public class CallBackTest {
  interface CallBackInterface {
    void callBackMethod();
  }
 
  class CallBackClass implements CallBackInterface {
 
    @Override
    public void callBackMethod() {
      System.out.println("hello");
    }
  }
 
  class Controller {
    private CallBackInterface cbitf;
    // 这个boolean只是为了模拟有事件,没啥实用价值
    public boolean somethingHappend;
    // 这里确实可以直接把CallBackClass做参数,而且省掉接口的定义
    // 但是这样做的话,就像是回调函数直接写在了调用函数里一样
    // 不明白的话就好好理解下"约定"和"调用者不管回调函数是怎么实现的"吧
    public Controller(CallBackInterface itfs) {
      somethingHappend = true;
      this.cbitf = itfs;
    }
 
    public void doSomething() {
      if(somethingHappend) {
        cbitf.callBackMethod();
      }
    }
  }
 
  public void showCallBack() {
    CallBackClass cbc = new CallBackClass();
    Controller ctrlr = new Controller(cbc);
    ctrlr.doSomething();
    // 其实上面也可以这样写在一行里
    // new Controller(new CallBackClass()).doSomething();
  }
}

Finally, let me say one more thing. In fact, this kind of application is often encountered in Android. I encountered it when I was learning Android.

The above is my personal understanding and usage of callback functions. I hope you all like it.

For more articles related to java callback functions, please pay attention to the PHP Chinese website!

Statement:
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