0

I have the following code:

final JsonObject source = source.toJson();
final JsonElement relatedSpace = source.get("myField");
if(relatedSpace.isJsonObject()){
  //do something
}

isJsonObject() does return instanceof JsonObject; according the the Gson code. instanceof should do a null check first, so I'm not sure how it's possible that my code is throwing a NullPointerException when relatedSpace is null. I can easily check for null first to fix the issue, but I'm wondering why this happens.

Razib
  • 10,965
  • 11
  • 53
  • 80
KPrince36
  • 2,886
  • 2
  • 21
  • 29

3 Answers3

3

The . operator is executed prior to the method after it.

If the object is null it will cause a NullPointerException, regardless to the content of the method.

SHG
  • 2,516
  • 1
  • 14
  • 20
2

Because relatedSpace is set to null (before you use it) in the situation you describing here. You actually get null from the following expression -

final JsonElement relatedSpace = source.get("myField"); 

(That means thee is no JsonElement with associated with the key "myField")

To avoiding null you may simply just check it before using it -

if(null!=relatedSpace && relatedSpace.isJsonObject()){
  //do something
}

For more on how to avoid NullPointerException you may check these nice suggestions

Razib
  • 10,965
  • 11
  • 53
  • 80
0

You are getting NPE because you are doing a method call on null reference. What you are confused about is between operator and methods in java. instanceof is an operator in java which works with null references too but the method calls on null reference is an exceptional condition and should be handled by null check.Other thing that you can do is to ditch the GSON method altogether and do a direct instance of check.

Swaraj Yadav
  • 83
  • 1
  • 6