[英]java.util.Objects.requireNonNull vs Preconditions.checkNotNull
The documentation for Guava Preconditions notes: Guava Preconditions的文档说明:
Projects which use
com.google.common
should generally avoid the use ofObjects.requireNonNull(Object)
.使用
com.google.common
项目通常应避免使用Objects.requireNonNull(Object)
。 Instead, use whichever ofcheckNotNull(Object)
orVerify.verifyNotNull(Object)
is appropriate to the situation.相反,使用
checkNotNull(Object)
或Verify.verifyNotNull(Object)
中适合的情况。 (The same goes for the message-accepting overloads.)(对于接收消息的重载也是如此。)
Can someone explain the rationale for this suggestion? 有人可以解释这个建议的理由吗?
Is it for the purpose of consistency or is there something fundamentally wrong with the implementation of Objects.requireNonNull
? 是为了保持一致性还是
Objects.requireNonNull
的实现存在根本性的错误?
It's just for consistency. 这只是为了保持一致性。 The implementations are the same.
实现是相同的。
Although from the example in the question it seems that OP is asking specifically about the particular form of checkNotNull
, there is one more subtle difference in general in favor of using checkNotNull
which is reflected in the printf
style varargs form. 虽然从问题中的例子来看,OP似乎是专门询问
checkNotNull
的特定形式,但是通常还有一个细微的区别,即支持使用checkNotNull
,这反映在printf
样式的varargs表单中。 For example using Guava Preconditions
you can do following: 例如,使用
Guava Preconditions
您可以执行以下操作:
public void getInput(String companyName) {
String context = "Google";
String moreContext = "Facebook";
checkNotNull(companyName, "Why not try %s or %s", context, moreContext);
}
with Objects.requireNonNull
you will have to do something like 使用
Objects.requireNonNull
你必须做类似的事情
public void getInput(String companyName) {
String context = "Google";
String moreContext = "Facebook";
requireNonNull(companyName, "Why not try " + context + " or " + moreContext);
}
Reference: See bottom section of Preconditions Explained 参考:参见前提条件说明的底部部分
Simple, varargs "printf-style" exception messages.
简单,varargs“printf-style”异常消息。 (This advantage is also why we recommend continuing to use checkNotNull over Objects.requireNonNull introduced in JDK 7.)
(这个优点也是我们建议继续在JDK 7中引入的Objects.requireNonNull上使用checkNotNull的原因。)
EDIT: One thing to note though is that all args to the errorMessageTemplate are converted to String using String.valueOf(arg)
so you can use only %s and not other type specifiers like %d or %f etc. 编辑:有一点需要注意的是,使用
String.valueOf(arg)
将errorMessageTemplate的所有参数转换为String,因此您只能使用%s而不能使用%d或%f等其他类型说明符。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.