我是 Java 8 的新手,正在尝试 Null 类型注释和 Optional。
对于下面的示例,我使用 String 而不是我的类,并且调用 toUpperCase 只是为了调用某些东西,在我的情况下,我实际上调用了一个传入参数的函数(所以不要认为我可以使用 :: 运算符和/或映射)。
在 Eclipse 中,我打开了 Java - 编译器 - 错误/警告 - 空分析错误。
我的测试代码如下:
public void test1(@Nullable String s) {
// the 2nd s2 has a Potential null pointer access error.
// I was hoping ifPresent would imply NonNull
Optional.ofNullable(s).ifPresent(s2 -> s2.toUpperCase());
}
@Nullable
public String getSomeString() {
return null;
}
public void test2() {
String s = getSomeString();
// This is fine, unlike the first example, I would have assumed that
// it would know s was still nullable and behave the same way.
Optional.ofNullable(s).ifPresent(s2 -> s2.toUpperCase());
}
使用 Eclipse 类型 null 注释和 Optional.ifPresent 似乎不能很好地结合在一起。
我是否在浪费时间试图让这样的事情发挥作用?我是否应该恢复将 getter 分配给 temp var,然后检查是否为 null,如果不调用我的函数?