强化:Java8的空解引用
当我在Java 8中有以下代码时,我在fortify中遇到空解引用问题:强化:Java8的空解引用,java,java-8,fortify,Java,Java 8,Fortify,当我在Java 8中有以下代码时,我在fortify中遇到空解引用问题: String name = statusList.stream() .map(s -> s.getNodeName()) .filter(n -> n.equalsIgnoreCase(temName)) .findFirst() .orElse(null); String parentName = name; if (parentName == null) { /
String name = statusList.stream()
.map(s -> s.getNodeName())
.filter(n -> n.equalsIgnoreCase(temName))
.findFirst()
.orElse(null);
String parentName = name;
if (parentName == null)
{
// if null code
}
else {
// Not Null code
}
我正在验证该值是否为null
。为什么我仍然会出错?我如何解决此问题以满足强化需求
更新:
我试图找到堆栈的踪迹,但没有什么结果
我也看到了这个错误:Assigned null:null(在orElse(null)上)
更新2:
这就是我看到的。没有大堆栈跟踪:
为什么需要精确的
null
?您可以使用isPresent()
可选选项name=statusList.stream()
.map(s->s.getNodeName())
.filter(Objects::notNull)//避免比较中出现null
.filter(n->n.equalsIgnoreCase(temName))//我假设temName不为null
.findFirst();
if(name.isPresent()){
//非空代码
}否则{
//空码
}
共享异常如何…您确定.map
调用中的节点名称属性不为空吗?我猜它是在抱怨流,而不是后续的代码。为了确保null
-安全,最好翻转equals并使用n->temName.equalsIgnoreCase(n)
作为谓词,如果temName
已知不是null
。您可以将其简化为temName::equalsIgnoreCase
。否则,应将null
作为参数传递给equalsIgnoreCase
。并确保statusList
和s
也不是null
@markrottevel,因为OP正在接收但未使用它。使用它意味着不调用.orElse(null)
,然后进行null
测试,而是首先使用,例如isPresent()
。我必须同意@Holger的观点orElse(null)
是一种明确的代码气味,它首先破坏了可选的整个点。
Optional<String> optionalName = statusList.stream()
.map(s -> s.getNodeName())
.filter(Objects::notNull) // to avoid nulls in comparation
.filter(n -> n.equalsIgnoreCase(temName)) // I assume temName is not null
.findFirst();
if (name.isPresent()) {
//not null code
} else {
//null code
}