在我的 Spring 项目中有一个服务
public Pageable<MyObject>findAccount(String accountExternalId){
if (accountExternalId== null) {
throw new ProjectException("Missing account");
}
...
}
因此,当我使用 java 5 个参数时,我必须创建 5 个 if 来检查空输入对象。为了不这样做,我想使用 javax.annotation.Nonnull 和 javax.annotation.CheckForNull 并执行类似的操作。
public Pageable<MyObject>findAccount(@Nonnull String accountExternalId){
...
}
并使用 findbugs
<groupId>
com.google.code.findbugs
</groupId>
<artifactId>
findbugs
</artifactId>
所以我想知道这个注释如何防止用户不传递 Null 值?或者它只是注释您不必传递 null 并且仅用于提供信息?
最佳答案
So I am wondering how this annotation prevent users not to pass Null values? Or it only annotate that you have not to pass null and is only with informational purpose?
第二个。
然而,FindBugs 也使用其中一些注释进行分析;例如,如果您有一个 @Nullable 参数(或方法返回值),并且 FindBugs 在代码中检测到您在使用该参数(或方法返回值)之前没有检查该参数(或方法返回值)是否为 null,这会引发一个问题。
如果@Nonnull
,那么它基本上表示调用者有责任确保将非 null 参数传递给方法或方法不返回 null。
(但不确定 @CheckForNull
和 @Nullable
之间的区别)
关于java - 了解@Nonnull和@CheckForNull注释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31099708/