我有一个这样的课程:
import javax.annotation.Nullable;
public class Nullness {
private @Nullable Object someObject;
public void foo() {
if (someObject != null) {
someObject.toString(); //error "Potential null pointer access: The field someObject is specified as @Nullable"
}
}
}
当启用eclipse null分析时,会在someObject.toString();
语句Potential null pointer access: The field someObject is specified as @Nullable
处标记错误。
Eclipse有一个快速修复,可以将我的代码更改为:
public void foo() {
final Object someObject2 = someObject;
if (someObject2 != null) {
someObject2.toString();
}
}
可以消除错误,请注意,实际上,不需要final
修饰符来使错误消失。
我不明白为什么Eclipse不允许我直接在空值检查语句if (someObject != null)
中使用字段变量,但强迫我创建其他局部变量someObject2
。这种行为只是一个错误还是故意的?