I don't understand what a callback method is and I have heard people use that term very loosely. In the Java world, what is a callback method? If someone could provide some example code of a Java callback method with an explanation, it would be a great help in my Java learning journey.
Thank you in advance.
解决方案
A callback is a piece of code that you pass as an argument to some other code so that it executes it. Since Java doesn't yet support function pointers, they are implemented as Command objects. Something like
public class Test {
public static void main(String[] args) throws Exception {
new Test().doWork(new Callback() { // implementing class
@Override
public void call() {
System.out.println("callback called");
}
});
}
public void doWork(Callback callback) {
System.out.println("doing work");
callback.call();
}
public interface Callback {
void call();
}
}
A callback will usually hold reference to some state to actually be useful.
By making the callback implementation have all the dependencies to your code, you gain indirection between your code and the code that is executing the callback.