3

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.

T. Junghans
  • 11,385
  • 7
  • 52
  • 75
  • Until Java 8, this is only possible using interfaces. – Luiggi Mendoza Nov 04 '13 at 15:14
  • Is there perhaps a different pattern then for solving this? – T. Junghans Nov 04 '13 at 15:15
  • Send an interface `MyInterface myInterface` that contains a `callback` method, then instead of `callback(ajaxResponse);` do `myInterface.callback(ajaxResponse);`. – Luiggi Mendoza Nov 04 '13 at 15:16
  • 1
    Also see http://www.javaworld.com/javatips/jw-javatip10.html for a more extensive explanation of how this is done in Java. – CompuChip Nov 04 '13 at 15:17
  • @LuiggiMendoza Slight nit, even with Java 8, it's still only possible with interfaces. What Java 8 gives you is that creating an anonymous class that implements the interface is easier, at the call site. To the function that uses the callback (e.g. `fetchData` above), nothing changes in Java 8. – yshavit Nov 04 '13 at 15:19

1 Answers1

3

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);
Paul Richter
  • 10,908
  • 10
  • 52
  • 85