Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Eclipse null check doesn't work with functions

Tags:

java

eclipse

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.

like image 255
Tezra Avatar asked Feb 06 '26 12:02

Tezra


2 Answers

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..

like image 135
Rob Avatar answered Feb 09 '26 08:02

Rob


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());
}
like image 21
Elliott Frisch Avatar answered Feb 09 '26 07:02

Elliott Frisch



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!