编程成语言:在Java中定义回调的最优雅方法是什么?

Mne*_*nth 4 java callback

在"代码完整"一书中,作者谈到了编程一种语言(而不是用语言编程).他的意思是,你不应该通过所选编程语言的限制来限制自己.

回调是一种常用的功能.我很感兴趣:将回调编程到java语言中最优雅的方法是什么?

Bra*_*ugh 6

Java为各种情况使用各种回调.自从AWT听众最古老的时代以来,Java一直都是关于回调的.

Java回调有两种基本的"风格".第一个是实现接口方法:

public class MyThing implements StateChangeListener {

   //this method is declared in StateChangeListener
   public void stateChanged() {
      System.out.println("Callback called!");
   }

   public MyThing() {
      //Here we declare ourselves as a listener, which will eventually
      //lead to the stateChanged method being called.
      SomeLibraryICareAbout.addListener(this);
   }
}
Run Code Online (Sandbox Code Playgroud)

Java回调的第二种风格是匿名内部类:

public class MyThing {

   public MyThing() {
      //Here we declare ourselves as a listener, which will eventually
      //lead to the stateChanged method being called.
      SomeLibraryICareAbout.addListener( new StateChangeListener() {
          //this method is declared in StateChangeListener
          public void stateChanged() {
              System.out.println("Callback called!");
          }
      });
   }
}
Run Code Online (Sandbox Code Playgroud)

还有其他方法,包括使用Reflection,使用单独的事件处理类和Adapter模式.