简体   繁体   中英

Eclipse null check doesn't work with functions

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.

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());
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM