I am getting a Potential null pointer access: The variable test may be null at this location eclipse warning from the below code.
public class Runtime {
public static void main(final String args[]) throws Exception {
Collection<String> test = null;
if (new Random().nextBoolean()) {
test = new ArrayList<>();
}
if (!isNullOrEmpty(test)) {
test.size();
}
}
public static boolean isNullOrEmpty(final Collection<?> coll) {
return (coll == null) || coll.isEmpty();
}
}
The act of checking isNullOrEmpty should guarantee that test is non-null. Making the function call inline will fix the problem, proving that this is just an eclipse limitation.
I don't want to ignore the warning, because I need to know if I forget to do the check, and I don't want to inline the same check 500 times (especially the more complex cases).
Is there anyway to adjust this so that eclipse knows test is not null when I call size?
I am using Java 8.
Does this do what you want? How can I annotate my helper method so Eclipse knows its argument is non null if it returns true?
Apparently (I have never use it) you can annotate the helper method with something like:
@EnsuresNonNullIf(expression="#1", result=true)
public static boolean isNullOrEmpty(final Collection<?> coll) { ...
It may require an add-on..
It really looks like you wanted an Optional instead of a Collection. In which case, you could use one. Like,
Optional<String> optional = Optional.ofNullable(null);
if (new Random().nextBoolean()) {
optional = Optional.of("somevalue");
}
if (optional.isPresent()) {
System.out.println(optional.get());
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With