dthree
dthree

Reputation: 20790

Shorthand callback on Java HTTP request

I am working on a Java app coming from a Javascript background.

I have the following code to implement an HTTP Get request:

HttpGetRequest get = new HttpGetRequest(new HttpGetRequest.CustomCallback() {
    @Override
    public void completionHandler(Boolean success, String result) throws JSONException, InterruptedException {
        // Do things here
    }
});
get.execute("https://foo.bar/status");

This works for me, however is there any way to use a callback in a little more terse manner, i.e. not having to instantiate an instance and override a class method?

I'm used something like fetch(url, () => { /* do things here */ }), and would like to know if this is approachable.

Upvotes: 1

Views: 1093

Answers (1)

Carcigenicate
Carcigenicate

Reputation: 45806

You can always use Functional Interfaces, although it requires some extra work.

@FunctionalInterface
public interface HTTPRequestHandler {
    public void completionHandler(Boolean success, String result) throws JSONException, InterruptedException;

}

public HttpGetRequest newHTTPRequest(HTTPRequestHandler f) {
    return new HttpGetRequest(new HttpGetRequest.CustomCallback() {
        public void completionHandler(Boolean success, String result) throws JSONException, InterruptedException {
            f.completionHandler(success, result);
        }
    });
}

Then use it like:

HttpGetRequest get = newHTTPRequest((success, result) -> { /* Do Stuff */ });

The functional interface allows for the lambda syntax. Unfortunately, CustomCallback doesn't seem to already implement a functional interface, so the newHTTPRequest wrapper function is necessary.

(Note, I haven't written Java in awhile. I'm straining my Java knowledge here. Hopefully someone can give you a better answer, but I figure this would suffice for lack of a better one.)

Upvotes: 1

Related Questions