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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With