第 1 章:Java 空值安全性注解系统
1.1 引言
1.1.1 空指针异常:Java 的'十亿美元错误'
- 历史背景:Tony Hoare 在 1965 年发明 null 引用,后称其为'十亿美元错误'
- 现实问题:空指针异常(NullPointerException)是 Java 中最常见的运行时异常之一
- 解决方案:通过注解提供编译时/开发时的空值安全检查
1.1.2 注解的角色定位
// 传统 Java 代码:无法从签名判断是否可能返回 null
public String getUserEmail(int id) {
// 实现可能返回 null,但调用者不知道
}
// 使用注解:明确契约
@Nullable
public String getUserEmail(int id) {
// 调用者知道可能需要处理 null
}
1.2 核心注解详解
1.2.1 @NotNull
定义:明确表示值不能为 null
@NotNull
public String getRequiredUsername() {
return "AlwaysReturnsValue";
}
工具行为:如果方法可能返回 null,会发出警告。
使用场景:
- 方法保证永不返回 null
- 参数必须非 null
- 字段初始化后不再为 null
1.2.2 @Nullable
定义:明确表示值可能为 null
@Nullable
public String findUserEmail(int userId) {
return userRepository.findById(userId)?.getEmail();
}
工具行为:对未检查的解引用发出警告。
使用场景:
- 方法可能返回 null
- 可选参数

