-->

Java Null Dereference when setting a field to null

2019-08-17 08:09发布

问题:

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's analysis trace says:

Assigned null: sortName
Branch taken: if (lastName != null && lastName.length() > 0)
Dereferenced: sortName

I could try:

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.

回答1:

What fortify do not like is the fact that you initialize the variable with null first, without condition, and then change it.

this should work:

String sortName;
if (lastName != null && lastName.length() > 0) {
   sortName = lastName;
} else {
   sortName = null;
}
sortOptions.setSortField(sortName);

(Or use the ternary operator if you prefer)

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.

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.



回答2:

Thierry's answer works great. This also passes Fortify's scan:

Optional<String> sortName = Optional.empty();
if (lastName != null && lastName.length() > 0) {
   sortName = Optional.ofNullable(lastName);
}
sortOptions.setSortField(sortName.orElse(null));


标签: java fortify