[英]@NonNullByDefault and @Nullable Evaluation in Eclipse
I am using the eclipse null annotations to check for possible NPE in my code.我正在使用 eclipse null 注释来检查我的代码中可能存在的 NPE。
Every class in my project has the @NonNullByDefault
annotation.我项目中的每个类都有
@NonNullByDefault
注释。 There are some fields that have the @Nullable
annotation.有一些字段具有
@Nullable
注释。
Here the problematic code:这里有问题的代码:
@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 );
}
}
}
This code now gives me the error message:这段代码现在给了我错误信息:
Null type mismatch (type annotations): required '@NonNull File' but this expression has type '@Nullable File'
and will not compile.并且不会编译。
When I change my method to:当我将方法更改为:
public void myMethod() {
...
File another = myFile;
if( another != null ) {
AnotherClass.callStaticFunction( another );
}
}
the code will compile without any complaints.代码将编译,没有任何抱怨。
Why is that so?为什么呢?
The online documentation contains a paragraph "The case of fields" which details the intricacies involved with accessing fields. 在线文档包含一段“字段案例”,其中详细说明了访问字段的复杂性。 Essentially, flow analysis can only make exact statements about variables which are owned by the current scope.
本质上,流分析只能对当前作用域拥有的变量做出准确的陈述。 Local variables are owned by the block in which they are declared, fields are not owned by any lexical scope, and hence are prone to unexpected effects due to any of
局部变量在声明它们,磁场不受任何词汇范围,所拥有的区块拥有的,因此容易出现意想不到的效果,由于任何的
- effects via aliased references
通过别名引用的效果
- side effects of another method
另一种方法的副作用
- concurrency
并发
The same help text also outlines the two possible solutions (short of introducing more annotations, eg, to specify ownership):相同的帮助文本还概述了两种可能的解决方案(没有引入更多注释,例如指定所有权):
The first of these strategies should normally be preferred and that's also what is mentioned in the question - so you should be fine.通常应该首选这些策略中的第一个,这也是问题中提到的 - 所以你应该没问题。
Finally, I should mention there exists an RFE to introduce an annotation like @LazyNonNull
, which would basically signal the following:最后,我应该提到存在一个RFE来引入像
@LazyNonNull
这样的注释,它基本上会发出以下信号:
null
.null
。null
to such a field.null
分配给这样的字段。
More comments expressing demand in this directions may help motivating investments towards such a solution.在此方向表达需求的更多评论可能有助于推动对此类解决方案的投资。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.