我从 sonarqube 得到了以下错误
A "NullPointerException" could be thrown; "getFolderPath()" can return null.
对于以下行:
if (upstreamContent.getFolderPath() != null && !upstreamContent.getFolderPath().isEmpty()) {
...
}
其中 upstreamContent 不能为 null。
如何在不关闭规则的情况下在 sonarqube 中修复它?
更新:
有人要我显示 UpstreamContent 的来源
public class UpstreamContent {
@Nullable
private String folderPath;
...
@CheckForNull
@Nullable
public String getFolderPath() {
return folderPath;
}
public void setFolderPath(String folderPath) {
this.folderPath = folderPath;
}
}
最佳答案
可能通过将结果保存到变量而不是调用两次:
String path = upstreamContent.getFolderPath();
if (path != null && !path.isEmpty()) {
...
}
也许你或我知道,如果它第一次不返回 null
,第二次就不会(实际上我不知道,因为我不知道什么是 upstreamContent
是 :-) ),但通用工具无法知道或假设这一点。就其所知,它可以在第一次返回非null
,在第二次返回null
。通过将调用结果保存到一个变量,我们确保 Sonarqube 和任何后来阅读和维护代码的人都知道,在调用 isEmpty 之前我们已经做了一个
。null
检查
事实上,既然您已经发布了upstreamContent
类的代码,getFolderPath
完全有可能返回非null
用于第一次调用,null
用于第二次调用(如果另一个线程在其间调用 setFolderPath(null)
)。
关于java - Sonarqube 说 : A "NullPointerException" could be thrown; "getFolderPath()" can return null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48203596/