开发者

Can we avoid npe while checking for null in nested java objects?

1) if(null != parentObj.childObj)

2) if(parentObj.childObj != null)

Do you thi开发者_开发技巧nk that "1" will avoid a potential null pointer exception in the case where 'parentObj' is null, in contrast to "2"?


No.

If parentObj is null then any attempt to call a method or reference a field will result in a NullPointerExcepton. != always evaluates both sides.

Just check if parentObj is null first and handle it appropriately.


Why not just if(parentObj != null && parentObj.childObj != null) ?


If parentObj is null, referencing any method/field on parentObj will result in an NPE. In other words, you need if (parentObj != null && parentObj.childObj != null) to avoid an NPE. Groovy cuts down on this (very common) type of verbosity with the safe navigation operator, which lets you write if (parentObj?.childObj).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜