【发布时间】:2018-02-21 20:22:22
【问题描述】:
在 Eclipse (4.7.2) 中设置 null analysis -> potential null access 给我一个警告。
给定以下代码:
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(例如,将其设置为"")将发明不存在的数据,我不能完全拥有NullString 对象(不能扩展String)来表示不存在的数据。
hasText(String s) 必须能够接受任何此类输入数据,因此必须能够接受null。
【问题讨论】:
-
我不明白你想要什么。我的意思是,您的
hasText参数是一个字符串 - 不是空值。而你试图通过null而不是String调用String s = (new Random().nextBoolean()) ? "valid" : null;尝试写String s = (new Random().nextBoolean()) ? "valid" : ""; -
@zlakad 如果数据不存在,则字符串可能为空,数据可能来自多种来源,我无法完全创建 NullString 对象来防止字符串可以为空。
-
好的。为什么不使用
Optional<String> mayBeNull;? -
仅供参考,
(s == null || s.trim().isEmpty()) ? false : true只是!(s == null || s.trim().isEmpty())或s != null && !s.trim().isEmpty()的简写。 -
@shmosel 哎呀。我刚刚将一个更大的 if-else 压缩到那个三元运算中,我突然想到我应该把它简化成一个布尔表达式。很好的收获。
标签: java eclipse null annotations compiler-warnings