@Nonnull和Objects.requireNonNull有什么区别 [英] What is the difference between @Nonnull and Objects.requireNonNull
问题描述
以下两个代码段之间有什么区别.
What is the difference between following two code snippets.
public Integer getId(@Nonnull SomeObject obj){
// do some stuff
return id;
}
public Integer getId(SomeObject obj){
Objects.requireNonNull(SomeObject, "SomeObject is null");
// do some stuff
return id;
}
它们之间的显着区别是什么.在这些情况下进行空值检查的正确方法是什么.
What are the significant differences between them. And what is the correct way to do the null-check in these situations.
推荐答案
两者是互补的: @Nonnull
注释记录了 obj
必须为非null的事实,而 Objects.requireNonNull
调用可确保 obj
在运行时不为空.
The two are complementary: @Nonnull
annotation documents the fact that obj
must be non-null, while Objects.requireNonNull
call ensures that obj
is non-null at run-time.
您应该将两者结合起来,像这样:
You should combine the two, like this:
public Integer getId(@Nonnull SomeObject obj){
Objects.requireNonNull(SomeObject, "SomeObject is null");
// do some stuff
return id;
}
@Nonnull
上的相关文档可以找到此处:
Relevant documentation on @Nonnull
can be found here:
可选的类型注释不能替代运行时验证
在类型注释之前,描述诸如可空性或范围之类的东西的主要位置在javadoc中.使用Type批注,这种通信以一种编译时验证的方式进入字节码.
Before Type Annotations, the primary location for describing things like nullability or ranges was in the javadoc. With Type annotations, this communication comes into the bytecode in a way for compile-time verification.
您的代码仍应执行运行时验证.
Your code should still perform runtime validation.
这篇关于@Nonnull和Objects.requireNonNull有什么区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!