java.util.Objects.requireNonNull 对比 Preconditions.checkNotNull
java.util.Objects.requireNonNull vs Preconditions.checkNotNull
Guava Preconditions 注释的文档:
Projects which use com.google.common
should generally avoid the use of
Objects.requireNonNull(Object)
. Instead, use whichever of
checkNotNull(Object)
or Verify.verifyNotNull(Object)
is appropriate to
the situation. (The same goes for the message-accepting overloads.)
有人可以解释这个建议的理由吗?
是为了保持一致性还是Objects.requireNonNull
的实现有根本性的错误?
这只是为了保持一致性。实现方式相同。
尽管从问题中的示例来看,OP 似乎专门询问了 checkNotNull
的特定形式,但总体上还有一个更细微的差异,有利于使用 checkNotNull
这反映了在 printf
样式的可变参数形式中。例如使用 Guava Preconditions
您可以执行以下操作:
public void getInput(String companyName) {
String context = "Google";
String moreContext = "Facebook";
checkNotNull(companyName, "Why not try %s or %s", context, moreContext);
}
对于Objects.requireNonNull
你将不得不做类似
的事情
public void getInput(String companyName) {
String context = "Google";
String moreContext = "Facebook";
requireNonNull(companyName, "Why not try " + context + " or " + moreContext);
}
参考:参见 Preconditions Explained
的底部
Simple, varargs "printf-style" exception messages. (This advantage is also why we recommend continuing to use checkNotNull over Objects.requireNonNull introduced in JDK 7.)
编辑:
需要注意的一件事是,errorMessageTemplate 的所有参数都使用 String.valueOf(arg)
转换为字符串,因此您只能使用 %s 而不能使用其他类型说明符,如 %d 或 %f 等
Guava Preconditions 注释的文档:
Projects which use
com.google.common
should generally avoid the use ofObjects.requireNonNull(Object)
. Instead, use whichever ofcheckNotNull(Object)
orVerify.verifyNotNull(Object)
is appropriate to the situation. (The same goes for the message-accepting overloads.)
有人可以解释这个建议的理由吗?
是为了保持一致性还是Objects.requireNonNull
的实现有根本性的错误?
这只是为了保持一致性。实现方式相同。
尽管从问题中的示例来看,OP 似乎专门询问了 checkNotNull
的特定形式,但总体上还有一个更细微的差异,有利于使用 checkNotNull
这反映了在 printf
样式的可变参数形式中。例如使用 Guava Preconditions
您可以执行以下操作:
public void getInput(String companyName) {
String context = "Google";
String moreContext = "Facebook";
checkNotNull(companyName, "Why not try %s or %s", context, moreContext);
}
对于Objects.requireNonNull
你将不得不做类似
public void getInput(String companyName) {
String context = "Google";
String moreContext = "Facebook";
requireNonNull(companyName, "Why not try " + context + " or " + moreContext);
}
参考:参见 Preconditions Explained
的底部Simple, varargs "printf-style" exception messages. (This advantage is also why we recommend continuing to use checkNotNull over Objects.requireNonNull introduced in JDK 7.)
编辑:
需要注意的一件事是,errorMessageTemplate 的所有参数都使用 String.valueOf(arg)
转换为字符串,因此您只能使用 %s 而不能使用其他类型说明符,如 %d 或 %f 等