使用 Preconditions.checkNotNull() 时如何避免“潜在的空指针访问”?

Aar*_*lla 5 java eclipse nullpointerexception guava

Eclipse 给我警告“潜在的空指针访问:变量 ann 在此位置可能为空”:

SomeAnnotation ann = type.getAnnotation( SomeAnnotation.class );
Preconditions.checkNotNull( ann, "Missing annotation on %s", type );

for( String value : ann.value() ) { // <-- warning happens here
}
Run Code Online (Sandbox Code Playgroud)

我正在使用 Eclipse 3.7 和Guava。有没有办法摆脱这个警告?

我可以使用SuppressWarnings("null"),但我必须将其附加到我认为是一个坏主意的方法中。

Aar*_*lla 1

Eclipse e4 对编译器中的 null 检查和资源跟踪有更好的支持。

另一个解决方案是编写您自己的版本,checkNotNull如下所示:

@Nonnull
public static <T> T checkNotNull(@Nullable T reference) {
  if (reference == null) {
    throw new NullPointerException();
  }
  return reference;   
}
Run Code Online (Sandbox Code Playgroud)

现在您可以使用这种方法:

SomeAnnotation ann = Preconditions.checkNotNull( type.getAnnotation( SomeAnnotation.class ) );
Run Code Online (Sandbox Code Playgroud)

(我省略了接受错误消息的版本checkNotNull();它们的工作方式相同)。

我想知道为什么 Guava 不这样做,因为他们已经在其他地方使用了这些注释。