Preconditions 的 Javadoc来自 Google 的 Guava 库指出:
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.)
此建议背后的动机是什么?我在 Javadoc 中找不到任何内容。
我的意思是,他们几乎做同样的事情,在这些情况下,通常最好使用标准 API(例如,Joda-Time 背后的人现在建议人们使用 java.time
,几乎是在贬低他们自己的框架)。
举个例子,这两行输入验证做同样的事情:
class PreconditionsExample {
private String string;
public PreconditionsExample(String string) {
this.string = Objects.requireNonNull(string, "string must not be null");
this.string = Preconditions.checkNotNull(string, "string must not be null");
}
}
最佳答案
Guava 的版本提供了许多接受格式字符串和参数的重载。引用PreconditionsExplained维基:
We preferred rolling our own preconditions checks over e.g. the comparable utilities from Apache Commons for a few reasons. Briefly:
...
- Simple, varargs "printf-style" exception messages. (This advantage is also why we recommend continuing to use
checkNotNull
over Objects.requireNonNull introduced in JDK 7.)
关于java - 如果使用来自 Guava 的 com.google.common,为什么不应该使用 Objects.requireNonNull()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41890890/