Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programming into a language: What is the most elegant way to define callbacks in Java?

Tags:

java

callback

In the book 'Code Complete' the author talks about programming into a language (instead of programming in a language). He means, that you should not limit yourself by the restrictions of the chosen programming-language.

A callback is an often used feature. I'm interested: What is the most elegant way to programm callbacks into the java-language?

like image 478
Mnementh Avatar asked Dec 14 '22 04:12

Mnementh


2 Answers

Java uses all sorts of callbacks for all sorts of situations. Ever since the oldest old days of AWT listeners, Java has been all about callbacks.

There are two basic "flavors" of Java callbacks. The first is the implement an interface method:

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);
   }
}

The second flavor of Java callback is the anonymous inner class:

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!");
          }
      });
   }
}

There are other ways, too, including using Reflection, using separate event-handling classes, and the Adapter pattern.

like image 94
Brandon Yarbrough Avatar answered Dec 27 '22 21:12

Brandon Yarbrough


The most common way I've seen to work around the absense of function pointers/delegates in Java is to use functors.

Basically, define an interface with a single method and use instances of it as your callback:

public interface Callback<T,V>{
  public T invoke(V context);
}

Its alot more verbose than the C/C++ or C# equivalents, but it works. An example of this pattern in the standard library is the Comparator interface.

like image 42
Kevin Montrose Avatar answered Dec 27 '22 20:12

Kevin Montrose