0

I came across this piece of code today :

client.post(getApplicationContext(),url, entity,"application/json", new JsonHttpResponseHandler() {
                @Override
                public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                  System.out.println(statusCode);
                }
                @Override
                public void onFailure(int statusCode, Header[] headers,String responseString, Throwable throwable) {
                    // called when response HTTP status is "4XX" (eg. 401, 403, 404)
                }
            })

What exactly is being attempted and is it even legal ? It does not throw any errors when compiling....

  • The method client.post is being passed a function body as an argument ? What does that resolve to ? What will be the lifetime of the function, as this is an asynchronous post, and the response might take a little while to receive depending on the connection. So at the time the response arrives, will the JsonHttpResponseHandler(), as defined here, be alive to process it ? – Sreenivasa Chary Feb 04 '21 at 12:17
  • That's an anonymous class. – fiveelements Feb 04 '21 at 12:17
  • No it is not a function body. An object is passed. And that object exists as long as the `post()` method keeps the reference to it! – GhostCat Feb 04 '21 at 12:52

1 Answers1

0

I suppose method parameter accepts object wich extends JsonHttpResponseHandler object. And here is passing such new object generated pragrammatically as anonymous class. So it is legal in java.

See https://docs.oracle.com/javase/tutorial/java/javaOO/anonymousclasses.html#syntax-of-anonymous-classes

Sergey Afinogenov
  • 2,137
  • 4
  • 13