guava - java.util.Objects.requireNonNull vs Preconditions.checkNotNull - Stack Overflow
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.
Read full article from guava - java.util.Objects.requireNonNull vs Preconditions.checkNotNull - Stack Overflow
No comments:
Post a Comment