【问题标题】:Sonarqube says: A "NullPointerException" could be thrown; "getFolderPath()" can return nullSonarqube 说:可能会抛出“NullPointerException”; “getFolderPath()”可以返回 null
【发布时间】:2018-06-20 13:52:27
【问题描述】:

我从 sonarqube 收到以下错误

可能会抛出“NullPointerException”; “getFolderPath()”可以返回 空。

对于以下行:

if (upstreamContent.getFolderPath() != null && !upstreamContent.getFolderPath().isEmpty()) {
   ...
}

upstreamContent 不能为空。

如何在不关闭规则的情况下在 sonarqube 中修复它?

更新:

有人让我显示 UpstreamContent 的来源

public class UpstreamContent {

    @Nullable
    private String folderPath;

    ...

    @CheckForNull
    @Nullable
    public String getFolderPath() {
        return folderPath;
    }

    public void setFolderPath(String folderPath) {
        this.folderPath = folderPath;
    }
}

【问题讨论】:

  • 您确定刷新了 SonarCube 分析吗?我觉得没问题。
  • 你能告诉upstreamContent的类型
  • "您确定您刷新了 SonarCube 分析吗?"是的,我确定。

标签: java sonarqube


【解决方案1】:

可能通过将结果保存到变量而不是调用两次:

String path = upstreamContent.getFolderPath();
if (path != null && !path.isEmpty()) {
   ...
}

也许你或我知道,如果第一次不返回 null,第二次也不会(实际上我不知道,因为我不知道 upstreamContent 是什么 :-) ),但通用工具无法知道或假设这一点。据它所知,它可能第一次返回非null,第二次返回null。通过将调用结果保存到一个变量中,我们确保 Sonarqube 和后来阅读和维护代码的任何人都知道,我们在调用 isEmpty 之前已经完成了 null 检查。

事实上,既然您已经发布了upstreamContent 类的代码,那么getFolderPath 完全有可能在第一次调用时返回非null 而在第二次调用时返回null(如果另一个线程调用setFolderPath(null) 之间)。

【讨论】:

  • 我认为它很有用,它解决了问题。我认为声纳可能认为 getFolderPath() 结果可能会有所不同。
  • 作为该工具背后的开发人员之一:这正是符号执行引擎所假设的:对该 getter 的两次调用可能会产生不同的结果,第一个为非 null,第二个为 null。
猜你喜欢
  • 2018-11-15
  • 2021-03-12
  • 2021-06-06
  • 1970-01-01
  • 1970-01-01
  • 2023-01-30
  • 2022-08-03
  • 1970-01-01
相关资源
最近更新 更多