1
    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?

Nagendra Nigade
  • 866
  • 2
  • 12
  • 28
  • Have you checked if `response` is `null` directly after `response = restTemplate.exchange(url, HttpMethod.POST,request,JsonNode.class);`? – deHaar Sep 10 '19 at 07:54
  • What does the javadoc for `isNull()` say? – Kayaman Sep 10 '19 at 07:54
  • 1
    If `response.getBody()` returns `null`, then calling any method on it, including `isNull()`, will cause a `NullPointerException`. – Jesper Sep 10 '19 at 07:57
  • Isn't `isNull()` checking if Value is null, and `!= null` check if reference to object is null? – SkypeDogg Sep 10 '19 at 07:57
  • See also: [What is a NullPointerException, and how do I fix it?](https://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it) – Jesper Sep 10 '19 at 07:58
  • @Jesper : I though response.getBody() will return JsonNode object with value as null. `@Nullable public T getBody() { return this.body; }` – Nagendra Nigade Sep 10 '19 at 08:12

2 Answers2

5

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
    }
}
Andrew Tobilko
  • 48,120
  • 14
  • 91
  • 142
3

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.

Scorpio
  • 2,309
  • 1
  • 27
  • 45