Creating a method inside the arguments list of a java method

47 Views Asked by At

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....

1

There are 1 best solutions below

0
On

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