[英]Sonarqube says: A “NullPointerException” could be thrown; “getFolderPath()” can return null
I get a following bug from sonarqube 我从sonarqube得到以下错误
A "NullPointerException" could be thrown;
可能会抛出“ NullPointerException”。 "getFolderPath()" can return null.
“ getFolderPath()”可以返回null。
for the following line: 对于以下行:
if (upstreamContent.getFolderPath() != null && !upstreamContent.getFolderPath().isEmpty()) {
...
}
Where upstreamContent may not be null. 其中上游内容不能为空。
How can I fix it in sonarqube without turning off the rule? 我如何在不关闭规则的情况下用声纳法修复它?
UPDATE: 更新:
Someone asked me to show the source of UpstreamContent 有人要求我显示UpstreamContent的来源
public class UpstreamContent {
@Nullable
private String folderPath;
...
@CheckForNull
@Nullable
public String getFolderPath() {
return folderPath;
}
public void setFolderPath(String folderPath) {
this.folderPath = folderPath;
}
}
Probably by saving the result to a variable rather than making the call twice: 可能是通过将结果保存到变量而不是两次调用:
String path = upstreamContent.getFolderPath();
if (path != null && !path.isEmpty()) {
...
}
Maybe you or I know that if it doesn't return null
the first time, it won't the second (I don't, actually, because I don't know what upstreamContent
is :-) ), but a general-purpose tool can't know or assume that. 也许您或我知道,如果它第一次不返回
null
,就不会第二次(实际上,我不知道,因为我不知道upstreamContent
是什么:-)),而是通用的工具无法知道或假设。 For all it knows, it could return non- null
the first time and null
the second. 对于所有它知道,它可能返回非
null
的第一次和null
第二。 By saving the call result to a variable, we ensure that Sonarqube and anyone coming along later to read and maintain the code knows, for sure, that we've done a null
check before calling isEmpty
. 通过将调用结果保存到变量中,我们可以确保Sonarqube和以后要阅读和维护代码的任何人都知道,在调用
isEmpty
之前,我们已经进行了null
检查。
In fact, now that you've posted the code for upstreamContent
's class, it's entirely possible for getFolderPath
to return non- null
for the first call and null
for the second (if another thread calls setFolderPath(null)
in-between). 事实上,现在你已经发布的代码
upstreamContent
的类,它是完全有可能的getFolderPath
返回非null
的第一个呼叫, null
(如果另一个线程调用第二setFolderPath(null)
在中间)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.