java - 如果使用来自 Guava 的 com.google.common,为什么不应该使用 Objects.requireNonNull()?

标签 java guava

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/

相关文章:

java - 在 LifeRay portlet 中使用 Alloy UI

java - 改进标题栏的用户界面

java - 使用迭代器填充集合

scala - 来自 Scala 和 Guava 的 Murmur3 的不同结果

java - 在Java中用字符串中的多个替换来替换多个字符?

java - 有界类型参数不允许访问适当对象的方法

java - 流式传输文件并在读取后移动它们

java - Sets.CartesianProduct 与 GWT 不兼容

java - Guava eventbus 内存限制

java - @Nonnull 注释只是标记?