问题
I'm getting NP_NULL_ON_SOME_PATH_FROM_RETURN_VALUE
in this snippet
final Integer id = Ints.tryParse(idString);
FailReason.NO_SUCH_THING.checkCondition(id!=null);
something.setId(id.intValue());
Here, checkCondition
works just like Preconditions.checkArgument except for it throws my own exception. Throwing NPE or IAE is not appropriate here, as it's checking an external input rather than a programming error.
FindBugs complains that "The return value from a method is dereferenced without a null check, and the return value of that method is one that should generally be checked for null. This may lead to a NullPointerException when the code is executed."
Can I teach FindBugs that checkCondition
never returns normally when the argument is false
?
回答1:
I (sort of) solved it by adding
assert id!=null;
It's redundant and ugly, but still less ugly than @SuppressFBWarnings
and more local.
回答2:
Try using java.util.Objects.requireNonNull to please FindBugs:
final Integer id = Ints.tryParse(idString);
FailReason.NO_SUCH_THING.checkCondition(id!=null);
something.setId(Objects.requireNonNull(id).intValue());
Or you might be able to use java.util.Objects.isNull to fool FindBugs.
final Integer id = Ints.tryParse(idString);
FailReason.NO_SUCH_THING.checkCondition(!Objects.isNull(id));
something.setId(id.intValue());
来源:https://stackoverflow.com/questions/23746395/getting-rid-of-np-null-on-some-path-from-return-value