gpt4 book ai didi

java - 验证变量为空警告

转载 作者:行者123 更新时间:2023-11-30 02:14:51 25 4
gpt4 key购买 nike

在 Eclipse (4.7.2) 中,将 null 分析 -> 潜在 null 访问 设置为向我发出警告。

给出以下代码:

public class Test {

// validator method
static boolean hasText(String s) {
return !(s == null || s.trim().isEmpty());
}

public static void main(String[] args) {
// s could come from anywhere and is null iff the data does not exist
String s = (new Random().nextBoolean()) ? "valid" : null;
if (hasText(s)) {
// Potential null pointer access: The variable s may be null at this location
System.out.println(s.length());
// ... do actual stuff ...
}
}
}

如何避免潜在的 null 警告? @NotNull 不起作用,因为 null 是有效输入,输出是 boolean

有没有办法告诉编译器,如果此验证方法返回 true,则验证值非空?

是否有更好的方法来处理这样的验证方法?

谢谢。

<小时/>

为了清晰起见,更新:

数据来自用户输入(来自 xml 或 .properties 文件),并且当且仅当数据确实存在时为 null。

从不生成 null (例如,将其设置为 "")将会发明不存在的数据,而且我不能完全拥有 NullString 对象(无法扩展 String)来表示不存在的数据。

hasText(String s) 必须能够接受任何此类输入数据,因此也必须能够接受 null

最佳答案

您的代码是安全的(它永远不会抛出空指针异常),但也许 Eclipse 的分析太弱而无法确定这一点。您应该考虑使用更强大的工具。

Checker FrameworkNullness Checker可以证明你的代码是安全的。您只需要表达 hasText 的约定:hasText 接受一个可能为空的参数,并且仅当其参数非空时才返回 true。

以下是如何表达这一点:

@EnsuresNonNullIf(expression="#1", result=true)
static boolean hasText(@Nullable String s) { ... }

(有关更多详细信息,请参阅 Javadoc for @EnsuresNonNullIf。)

这是完整的示例,空值检查器会在没有警告的情况下验证该示例:

import java.util.Random;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.checkerframework.checker.nullness.qual.EnsuresNonNullIf;

public class Test {

// validator method
@EnsuresNonNullIf(expression="#1", result=true)
static boolean hasText(@Nullable String s) {
return !(s == null || s.trim().isEmpty());
}

public static void main(String[] args) {
// s could come from anywhere and is null iff the data does not exist
String s = (new Random().nextBoolean()) ? "valid" : null;
if (hasText(s)) {
// Potential null pointer access: The variable s may be null at this location
System.out.println(s.length());
// ... do actual stuff ...
}
}
}

关于java - 验证变量为空警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48914806/

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