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.

5
  • Until Java 8, this is only possible using interfaces. Commented Nov 4, 2013 at 15:14
  • Is there perhaps a different pattern then for solving this? Commented Nov 4, 2013 at 15:15
  • Send an interface MyInterface myInterface that contains a callback method, then instead of callback(ajaxResponse); do myInterface.callback(ajaxResponse);. Commented Nov 4, 2013 at 15:16
  • 1
    Also see javaworld.com/javatips/jw-javatip10.html for a more extensive explanation of how this is done in Java. Commented Nov 4, 2013 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. Commented Nov 4, 2013 at 15:19

1 Answer 1

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);
Sign up to request clarification or add additional context in comments.

2 Comments

Yes, this is covered in the possible duplicate Q/A.
@LuiggiMendoza Yes, I didn't notice that until after I posted the answer. My bad.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.