Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/355.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java Eclipse空检查不使用';我不能处理函数_Java_Eclipse - Fatal编程技术网

Java Eclipse空检查不使用';我不能处理函数

Java Eclipse空检查不使用';我不能处理函数,java,eclipse,Java,Eclipse,我得到一个潜在的空指针访问:变量测试可能在这个位置为空下面代码中的eclipse警告 public class Runtime { public static void main(final String args[]) throws Exception { Collection<String> test = null; if (new Random().nextBoolean()) { test = new Arra

我得到一个
潜在的空指针访问:变量测试可能在这个位置为空
下面代码中的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();
    }

}
公共类运行时{
公共静态void main(最终字符串args[])引发异常{
集合测试=null;
if(new Random().nextBoolean()){
测试=新的ArrayList();
}
如果(!isNullOrEmpty(测试)){
test.size();
}
}
公共静态布尔值isNullOrEmpty(最终集合coll){
return(coll==null)| | coll.isEmpty();
}
}
检查isNullOrEmpty的行为应该保证测试是非null的。将函数调用内联将解决问题,证明这只是eclipse的限制

我不想忽略这个警告,因为我需要知道是否忘记执行检查,并且我不想将同一个检查内联500次(尤其是更复杂的情况)

在调用size时,是否有任何方法来调整它,以便eclipse知道test不是null


我正在使用Java 8。

真的看起来你想要的是一个而不是
集合。在这种情况下,您可以使用一个。像

Optional<String> optional = Optional.ofNullable(null);
if (new Random().nextBoolean()) {
    optional = Optional.of("somevalue");
}
if (optional.isPresent()) {
    System.out.println(optional.get());
}
Optional=Optional.ofNullable(null);
if(new Random().nextBoolean()){
optional=optional.of(“somevalue”);
}
if(可选的.isPresent()){
System.out.println(可选的.get());
}

这是否符合您的要求?

显然(我从未使用过)您可以使用以下内容注释helper方法:

 @EnsuresNonNullIf(expression="#1", result=true)
 public static boolean isNullOrEmpty(final Collection<?> coll) { ...
@EnsuresNonNullIf(表达式=“#1”,结果=真)
公共静态布尔值isNullOrEmpty(最终集合coll){。。。

它可能需要一个附加组件。

可选。ofNullable(null)
可以短接到
可选。empty()
。否。集合是我想要的,因为我想处理一个值列表。不过,测试的类型并不重要,只是可以安全地从中调用方法。因为
可选。get().length();
如果调用
isPresent()失败,将抛出空指针异常
首先,这似乎更像是一种将空指针标志设置为忽略的冗长方式。这不是我想要的行为。如果我记得在使用它们之前检查东西,我就不需要空指针标志了。^^^;这是一种解决方案……尽管它需要检查框架。设置起来很复杂。我有点担心希望有一个配置或插件可以做到这一点。^;