简体   繁体   English

Eclipse null检查不适用于函数

[英]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. 我得到一个Potential null pointer access: The variable test may be null at this location eclipse警告来自下面的代码。

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. 检查isNullOrEmpty的行为应该保证测试非空。 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). 我不想忽略警告,因为我需要知道我是否忘记进行检查,而且我不想将相同的检查内联500次(尤其是更复杂的情况)。

Is there anyway to adjust this so that eclipse knows test is not null when I call size? 反正有调整这个,以便当我调用大小时eclipse知道test不为null吗?

I am using Java 8. 我使用的是Java 8。

It really looks like you wanted an Optional instead of a Collection . 看起来你真的想要一个Optional而不是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? 我如何注释我的助手方法,以便Eclipse知道如果返回true,则其参数为非null?

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.. 它可能需要一个附件..

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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