Sonarqube:不应取消引用空指针

Sonarcube :Null pointers should not be dereferenced

假设 DefaultMessageSourceResolvable 是 spring 框架 class 并且方法 getCode() 可能 return null

@SuppressWarnings("serial")
public class DefaultMessageSourceResolvable implements MessageSourceResolvable, Serializable {

    @Nullable
    private final String[] codes;

    @Nullable
    public String getCode() {
        return (this.codes != null && this.codes.length > 0 ? this.codes[this.codes.length - 1] : null);
    }

}

在另一个 class 中使用 getCode() 方法 Sonar Lint 给出错误:

A "NullPointerException" could be thrown; "getCode()" can return null.

//inside this test class we are checking the condition what the getCode() method return 
//and then performing some task 
class Test {

    DefaultMessageSourceResolvable error = new DefaultMessageSourceResolvable();

    if (error.getCode().contains("something"))
    //error.getCode() this may return null so sonar gives 
    //major  issue
    {
        //do something 
    }

}

如何解决这个问题?

您需要在使用 String#contains 方法之前检查空引用。

class Test {

    DefaultMessageSourceResolvable error = new DefaultMessageSourceResolvable();

    // Java with no third party libraries
    String errorCode = error.getCode();
    if (errorCode != null && errorCode.contains("something"))
    {
        //do something 
    }

    // Java using the very popular "org.apache.commons.lang3.StringUtils" library
    if (StringUtils.contains(error.getCode(), "something"))
    {
        //do something 
    }
}