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

Why should Objects.requireNonNull() not be used if com.google.common from Guava is used?

Google 的 Guava 库中 Preconditions 的 Javadoc 指出:

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 wiki:

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

据我所知,

  1. 为了一致性
  2. 如需其他方式执行以下操作,

    String world = "world"; Preconditions.checkNotNull(string, "Hello %s",world);

对于对象,您必须使用 String.format。此外,这两种方法的实现是相同的。