[英]How to remove 'nullness annotation is redundant' warning when using @NonNullByDefault and arrays? (Eclipse, NullAnnotation)
[英]@NonNullByDefault and @Nullable Evaluation in Eclipse
我正在使用 eclipse null 注释来检查我的代码中可能存在的 NPE。
我项目中的每个类都有@NonNullByDefault
注释。 有一些字段具有@Nullable
注释。
这里有问题的代码:
@NonNullByDefault
public class MyClass{
@Nullable
private File myFile;
public MyClass() {
...
// Somewhere here myFile may or may not be initialised
...
myMethod();
}
public void myMethod() {
...
if( myFile != null ) {
//AnotherClass also has @NonNullByDefault on it
AnotherClass.callStaticFunction( myFile );
}
}
}
这段代码现在给了我错误信息:
Null type mismatch (type annotations): required '@NonNull File' but this expression has type '@Nullable File'
并且不会编译。
当我将方法更改为:
public void myMethod() {
...
File another = myFile;
if( another != null ) {
AnotherClass.callStaticFunction( another );
}
}
代码将编译,没有任何抱怨。
为什么呢?
在线文档包含一段“字段案例”,其中详细说明了访问字段的复杂性。 本质上,流分析只能对当前作用域拥有的变量做出准确的陈述。 局部变量在声明它们,磁场不受任何词汇范围,所拥有的区块拥有的,因此容易出现意想不到的效果,由于任何的
- 通过别名引用的效果
- 另一种方法的副作用
- 并发
相同的帮助文本还概述了两种可能的解决方案(没有引入更多注释,例如指定所有权):
通常应该首选这些策略中的第一个,这也是问题中提到的 - 所以你应该没问题。
最后,我应该提到存在一个RFE来引入像@LazyNonNull
这样的注释,它基本上会发出以下信号:
null
。null
分配给这样的字段。
在此方向表达需求的更多评论可能有助于推动对此类解决方案的投资。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.