Search code examples
javanullpointerexceptiongsonnul

Gson isJsonObject() throws NullPointerException


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.


Solution

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