简体   繁体   中英

java.util.Objects.requireNonNull vs Preconditions.checkNotNull

The documentation for Guava Preconditions notes:

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.)

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 ?

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. For example using Guava Preconditions you can do following:

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

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. (This advantage is also why we recommend continuing to use checkNotNull over Objects.requireNonNull introduced in JDK 7.)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM