Possible Duplicate:
What's the nearest substitute for a function pointer in Java?
Callback functions in Java
I would like to ask some concept of the term callback.
What is the main purpose of using callback? Is it only for doing some async function? from the wiki, i can’t get what does actually means.
This part of code is copied from wiki- callback
void PrintTwoNumbers(int (*numberSource)(void)) {
printf("%d and %d\n", numberSource(), numberSource());
}
/* One possible callback. */
int overNineThousand(void) {
return (rand() % 1000) + 9000;
}
/* Here we call PrintTwoNumbers() with three different callbacks. */
int main(void) {
PrintTwoNumbers(overNineThousand);
}
from the wiki, it said the we need to pass a function pointer as arguments to other functions in order to do a callback.
But in java, there is no way to pass-by-references when we call a function, can we make a callback function in Java just like above code?
Thanks
Up until now, Java has used interfaces and (sometimes anonymous) implementations of said interfaces to behave as callbacks.
For simple callbacks, you can use
java.util.Runnableorjava.util.concurrent.Callableinstead of defining your own interfaces.Upcoming versions of Java will add better support for doing elegant callbacks, see this.