gpt4 book ai didi

java - Eclipse 空检查不适用于函数

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:08:45 26 4
gpt4 key购买 nike

我收到来自以下代码的 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();
}

}

检查 isNullOrEmpty 的行为应该保证测试是非空的。使函数调用内联将解决问题,证明这只是 eclipse 的限制。

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

有没有办法调整它,以便在我调用 size 时 eclipse 知道测试不为空?

我正在使用 Java 8。

最佳答案

这是否符合您的要求? How can I annotate my helper method so Eclipse knows its argument is non null if it returns true?

显然(我从未使用过它)你可以用类似的东西注释辅助方法:

 @EnsuresNonNullIf(expression="#1", result=true)
public static boolean isNullOrEmpty(final Collection<?> coll) { ...

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

关于java - Eclipse 空检查不适用于函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49657920/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com