NullPointerException 将在方法调用时抛出

NullPointerException will be thrown on method call

我有一个简单的方法:

public String getValue(String tag)    {
    if (StringUtils.isBlank(tag))    {
        return null;
    }

    return tag.substring(tag.lastIndexOf('/') + 1).trim();
}

稍后会这样调用:

String tag = node.getNodeValue(); <-- from org.w3c.dom.Node
String value = getValue(tag);

String price = getAttribute(param1, param2, getValue(value));

SonarQube 警告我 NullPointerException:

"NullPointerException" will be thrown when invoking method "getValue()" <-- the second call

但是,我看不出如何。该方法本身是 null-proof 的。怎么了 ? SonarQube 无法使用 StringUtils.isBlank 方法吗?还是 getAttribute() 方法会给我 NullPointerException,并且错误消息似乎具有误导性?

您收到此警告是因为以下行:

return null;

为什么 return nulltag 是空白的时候?我建议你这样做:

return tag;

或者也许

return "";

但是,您的函数仍然容易出现 NullPointerException,因为 tag 可能是 null。为了避免出现 NullPointerException 的可能性,我建议您对函数进行以下实现:

public String getValue(String tag) {
    if (tag != null) {
        tag = tag.substring(tag.lastIndexOf('/') + 1).trim();
    }

    return tag;
}

如果字符串为 null,则不能对其调用任何方法。

trim方法会触发空指针异常:

 return tag.substring(tag.lastIndexOf('/') + 1).trim();

考虑对字符串使用可选: https://docs.oracle.com/javase/8/docs/api/java/util/Optional.html