Nagendra Nigade
Nagendra Nigade

Reputation: 876

Java "Null Pointer Exception" - responseEntity.getBody().isNull()

    ResponseEntity<JsonNode> response = null;

    //Calling POST Method
    response=restTemplate.exchange(url, HttpMethod.POST,request,JsonNode.class);
    restResponse.setStatusCode(response.getStatusCode());
    restResponse.setHeaders(response.getHeaders());
    if(response.getBody().isNull())
    {
        //DO SOMETHING
    }

Issue: Facing Null Pointer Exception

Eventhough I am trying to handle Not Null scenario using check response.getBody().isNull() , but seems like this check also leads to null pointer exeception.

My assumptions : response.getBody() should return me JsonNode object on which I am trying to execute isNull() method. I am not sure how this call again lead to Null Pointer Exception. On Intellij It shows as getBody() method is @Nullable there are chances of Null pointer exception.

I searched online some solution says to use response.getBody()!=null will work. I am confused. Then what is use of isNull() method?

Upvotes: 1

Views: 9122

Answers (2)

Andrew
Andrew

Reputation: 49606

I would use HttpEntity#hasBody before retrieving the body. There is a good chance the entity doesn't have a body. It's more expressive than a response.getBody() != null check.

Please, don't assume that isNull() on an object would check that object on null. this == null is fundamentally wrong and never true.

class Body {
    public boolean isNull() {
        return this == null; // never makes sense
    }
}

Upvotes: 5

Scorpio
Scorpio

Reputation: 2327

The isNull() method does not check whether the body field is null, it checks wether it was created from a NULL value.

From the Javadoc:

/**
 * Method that can be used to check if this node was created from
 * JSON literal null value.
 */

Its confusingly named, but remember: You cannot call a method on nothing (hence the NullPointerException). The answer you found earlier is true, to verify if that object is null itself, you need to work with a != null check.

Upvotes: 3

Related Questions