I am experienced in JavaScript but new to Java. I am trying to figure out how to pass a function as a parameter of another function. In JavaScript this would like the block in Figure 1.
Figure 1
function fetchData(url, callback) {
// Do ajax request and fetch data from possibly slow server
// When the request is done, call the callback function
callback(ajaxResponse);
}
Is there a similar way of doing this in Java? I have searched the internets, but found little that is helpful on a novice level.
Unfortunately, the only equivalent (that I know if) is defining an interface which your fetchData method will accept as a parameter, and instantiate an anonymous inner class using that interface. Or, the class calling the fetchData method can implement that interface itself and pass its own reference using this to method.
This is your method which accepts a "callback":
public void fetchData(String url, AjaxCompleteHandler callback){
// do stuff...
callback.handleAction(someData);
}
The definition of AjaxCompleteHandler
public interface AjaxCompleteHandler{
public void handleAction(String someData);
}
Anonymous inner class:
fetchData(targetUrl, new AjaxCompleteHandler(){
public void handleAction(String someData){
// do something with data
}
});
Or, if your class implements MyCoolInterface, you can simply call it like so:
fetchData(targetUrl, this);
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