我刚刚开始使用@NotNull
使用 Java 8 进行注释并得到一些意想不到的结果。
我有一个这样的方法:
public List<Found> findStuff(@NotNull List<Searching> searchingList) {
... code here ...
}
我编写了一个 JUnit 测试,为参数搜索列表传入空值。我预计会发生某种类型的错误,但它就像注释不存在一样。这是预期的行为吗?据我了解,这是为了让您跳过编写样板空检查代码。
非常感谢对 @NotNull 到底应该做什么的解释。
@Nullable
and @NotNull
自己什么都不做。它们应该充当文档工具。
The @Nullable
注释提醒您在以下情况下引入 NPE 检查的必要性:
- 调用可以返回 null 的方法。
- 取消引用可以为 null 的变量(字段、局部变量、参数)。
The @NotNull
注释实际上是一个明确的契约,声明以下内容:
- 方法不应返回 null。
- A variable (like fields, local variables, and parameters)
cannot should not hold null value.
例如,不要写:
/**
* @param aX should not be null
*/
public void setX(final Object aX ) {
// some code
}
您可以使用:
public void setX(@NotNull final Object aX ) {
// some code
}
此外,@NotNull
经常被检查约束验证器 https://docs.oracle.com/javaee/7/api/javax/validation/ConstraintValidator.html(例如在 Spring 和 Hibernate 中)。
The @NotNull
注释本身不会进行任何验证,因为注释定义 https://docs.oracle.com/javaee/7/api/javax/validation/constraints/NotNull.html不提供任何ConstraintValidator
类型参考。
欲了解更多信息,请参阅:
- Bean 验证 https://beanvalidation.org/2.0/
- 注释类型NotNull https://docs.oracle.com/javaee/7/api/javax/validation/constraints/NotNull.html
- 注释类型Constraint https://docs.oracle.com/javaee/7/api/javax/validation/Constraint.html
- 界面ConstraintValidator https://docs.oracle.com/javaee/7/api/javax/validation/ConstraintValidator.html
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)