将字段设置为null时Java Null取消引用-Fortify [英] Java Null Dereference when setting a field to null - Fortify
问题描述
当我将字段设置为null时,Fortify抱怨Null取消引用:
Fortify is complaining about a Null Dereference when I set a field to null:
String sortName = null;
if (lastName != null && lastName.length() > 0) {
sortName = lastName;
}
sortOptions.setSortField(sortName); <-- Fortify Null Dereference
Fortify的分析轨迹显示:
Fortify's analysis trace says:
Assigned null: sortName
Branch taken: if (lastName != null && lastName.length() > 0)
Dereferenced: sortName
我可以尝试:
if (sortName == null)
sortOptions.setSortField(null);
else
sortOptions.setSortField(sortName);
但这似乎很愚蠢.有人有经验吗?我宁愿摆脱发现,还是先注销它.
But that seems really silly. Anyone have experience with this one? I'd prefer to get rid of the finding vs. just write it off.
推荐答案
要加强的一点是,首先使用无条件的 null
初始化变量,然后再进行更改.
What fortify do not like is the fact that you initialize the variable with null
first, without condition, and then change it.
这应该起作用:
String sortName;
if (lastName != null && lastName.length() > 0) {
sortName = lastName;
} else {
sortName = null;
}
sortOptions.setSortField(sortName);
(或根据需要使用三元运算符)
(Or use the ternary operator if you prefer)
这样,您只初始化一次 sortName
,并明确表明 null
值在某些情况下是正确的,而不是您忘记了某些情况,从而导致变量在意外情况下保持 null
的状态.
This way you initialize sortName
only once, and explicitely show that a null
value is the right one in some cases, and not that you forgot some cases, leading to a var staying null
while it is unexpected.
空取消引用错误是在代码 sortName = lastName;
的行上,而不是setter的调用:forify不想让您有条件地更改a的值设置为 null
而不在所有分支中都这样做的变量.
The Null dereference error was on the line of code sortName = lastName;
not the call of the setter : fortify do not want you to conditionnally change the value of a variable that was set to null
without doing so in all the branches.
这篇关于将字段设置为null时Java Null取消引用-Fortify的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!