【问题标题】:Sonarcube :Null pointers should not be dereferencedSonarqube:不应取消引用空指针
【发布时间】:2021-05-01 07:47:13
【问题描述】:

假设 DefaultMessageSourceResolvable 是 spring 框架类,方法 getCode() 可能返回 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);
    }

}

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

可能会抛出“NullPointerException”; "getCode()" 可以返回 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 
    }

}

如何解决这个问题?

【问题讨论】:

    标签: spring-mvc sonarqube


    【解决方案1】:

    在使用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 
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-03-17
      • 2018-10-05
      • 2013-02-20
      • 2022-01-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多