Gracefully avoiding NullPointerException in Java

前端 未结 9 1385
夕颜
夕颜 2020-11-30 04:02

Consider this line:

if (object.getAttribute(\"someAttr\").equals(\"true\")) { // ....

Obviously this line is a potential bug, the attribute

9条回答
  •  旧巷少年郎
    2020-11-30 04:36

    In the second option, you can take advantage of short-circuiting &&:

    String attr = object.getAttribute("someAttr");
    if (attr != null && attr.equals("true")) { // ....
    

提交回复
热议问题