Skip to main content
 首页 » 编程设计

java中Eclipse 中的 @NonNullByDefault 和 @Nullable 求值

2025年12月25日23三少

我正在使用 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 ); 
    } 
} 

代码将毫无怨言地编译。

为什么会这样?

请您参考如下方法:

online documentation包含一段“字段的情况”,其中详细说明了访问字段所涉及的复杂性。本质上,流分析只能对当前作用域拥有的变量做出准确的陈述。局部变量由声明它们的 block 拥有,字段由任何词法作用域拥有,因此很容易由于以下任何原因而产生意外影响

  • effects via aliased references
  • side effects of another method
  • concurrency

相同的帮助文本还概述了两种可能的解决方案(无需引入更多注释,例如指定所有权):

  • 处理前分配给局部变量
  • “语法分析”,它识别一组有限的模式,这些模式在正常情况下足够安全(在这种情况下没有给出完全保证)。

这些策略中的第一个通常应该是首选,这也是问题中提到的 - 所以你应该没问题。

最后,我应该提到存在一个 RFE引入像 @LazyNonNull 这样的注释,它基本上会发出以下信号:

  • 没有必要在所有构造函数中初始化这些字段。
    • 因此,该字段可能为 null
  • 无法为此类字段分配 null
    • 因此,对该字段进行 null 检查足以在检查后假设非 null。

更多表达这方面需求的评论可能有助于激励对此类解决方案的投资。