[英]Why checkNotNull() is not annotated with @Nonnull
I found inconvenient that checkNotNull()
precondition in guava is not marked with @Nonull
annotation. 我发现不方便之处在于番石榴中的
checkNotNull()
前提条件未使用@Nonull
批注标记。 Consider following example: 考虑以下示例:
State(Set<Model> models, Set<Variation> variations) {
this.models = checkNotNull(models);
this.variations = checkNotNull(variations);
if (this.variations == null) {
throw new IllegalArgumentException();
}
this.engine = createEngine();
}
So IDE could not found that variations == null
is always false. 因此,IDE无法发现
variations == null
始终为false。 Is there any particular reasons why this precondition is not marked with @Nonull
(even if it's arguments are defined using @Nullable
). 是否有任何特殊原因为何此先决条件没有用
@Nonull
标记(即使其参数是使用@Nullable
定义的)。
We haven't used @Nonnull
anywhere , sorry. 很抱歉, 我们没有在任何地方使用
@Nonnull
。 Why? 为什么? We tried adding more null-checking annotations, and we found that:
我们尝试添加更多的空检查注释,发现:
@Nullable
is all we need for NullPointerTester
. @Nullable
是NullPointerTester
所需的全部。 Admittedly that's more important to Guava developers than Guava users. @Nullable
appeared to have caught most problems. @Nullable
似乎遇到了大多数问题。 I admit it's hard to say how many un-checked-in bugs other annotations would have caught before the user found them. The verbosity was the main thing. 详细是最主要的。 It gets crazy, especially with subtyping and with parameterized types.
它变得很疯狂,尤其是对于子类型化和参数化类型。 We tried to pick a sweet spot for annotations.
我们试图为注释选择一个最佳位置。 Maybe we'll change it one day.
也许有一天我们会更改它。 For the moment, though, that's why things are the way they are.
但就目前而言,这就是事情按原样进行的原因。
(If we did do something, I suspect we'd try to make @Nonnull
the default, using @CheckForNull
for the exceptions instead. But I haven't looked into it even enough to make sure I've got the meanings right.) (如果我们做了某些事情,我怀疑我们会尝试将
@Nonnull
为默认值,而是使用@CheckForNull
作为例外。但是我还没有仔细研究它以确保我理解了正确的含义。)
It would indeed be interesting to annotate its result with @Nonnull
, since checkNotNull()
throws a NPE if the reference is null
, which means it never returns null
: 用
@Nonnull
注释其结果确实很有趣,因为如果引用为null
,则checkNotNull()
会引发NPE,这意味着它永远不会返回null
:
@Nonnull
public static <T> T checkNotNull(T reference) {
if (reference == null) {
throw new NullPointerException();
}
return reference;
}
Note that you'd need to change your code to: 请注意,您需要将代码更改为:
if(this.variations == null)
since the @Nonnull
would only apply to the result of checkNotNull()
, but says nothing about its argument. 因为
@Nonnull
仅适用于checkNotNull()
的结果,但对其参数一无所知。 Note that we cannot annotate the argument with @Nonnull
, since we might often be checking nullable variables. 注意,我们不能用
@Nonnull
注释参数,因为我们可能经常检查可为空的变量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.