在方法参数中使用NotNull Annotation [英] Using NotNull Annotation in method argument
问题描述
我刚刚开始在Java 8中使用 @NotNull
注释并获得一些意想不到的结果。
I just started using the @NotNull
annotation with Java 8 and getting some unexpected results.
我有这样的方法:
public List<Found> findStuff(@NotNull List<Searching> searchingList) {
... code here ...
}
我写了一个JUnit测试,传递参数searchList的null值。我期待发生某种类型的错误,但它经历了好像注释不在那里。这是预期的行为吗?根据我的理解,这是为了让你跳过编写样板空检查代码。
I wrote a JUnit test passing in the null value for the argument searchingList. I was expecting some type of error to happen but it went through as though the annotation was not there. Is this expected behavior? From what I understood, this was to allow you to skip writing the boilerplate null check code.
对@NotNull应该做什么的解释将不胜感激。
An explanation of what exactly @NotNull is supposed to do would be greatly appreciated.
推荐答案
@Nullable
和 @NotNull
自己不做任何事。它们应该充当文档工具。
@Nullable
and @NotNull
do nothing on their own. They are supposed to act as Documentation tools.
@Nullable
注释提醒您引入NPE的必要性检查何时:
The @Nullable
Annotation reminds you about the necessity to introduce an NPE check when:
- 调用可返回null的方法。
- 取消引用变量(字段,局部变量) ,参数)可以为null。
@NotNull
注释是,实际上,明确的合同声明如下:
The @NotNull
Annotation is, actually, an explicit contract declaring the following:
- 方法不应返回null。
- A变量(如字段,局部变量和参数)不能保存空值。
例如,而不是写作:
/**
* @param aX should not be null
*/
public void setX(final Object aX ) {
// some code
}
您可以使用:
public void setX(@NotNull final Object aX ) {
// some code
}
这篇关于在方法参数中使用NotNull Annotation的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!