Eclipse给我警告“潜在空指针访问:变量ann在此位置可能为null”:
SomeAnnotation ann = type.getAnnotation( SomeAnnotation.class );
Preconditions.checkNotNull( ann, "Missing annotation on %s", type );
for( String value : ann.value() ) { //
}
我正在使用Eclipse 3.7和Guava.有没有办法摆脱这个警告?
我可以使用SuppressWarnings(“null”),但我必须将它附加到我认为不太好的方法.
解决方法:
Eclipse e4对编译器中的空检查和资源跟踪有更好的支持.
另一种解决方案是编写自己的checkNotNull版本,如下所示:
@Nonnull
public static T checkNotNull(@Nullable T reference) {
if (reference == null) {
throw new NullPointerException();
}
return reference;
}
现在你可以使用这种方法:
SomeAnnotation ann = Preconditions.checkNotNull( type.getAnnotation( SomeAnnotation.class ) );
(我省略了带有错误消息的checkNotNull()版本;它们以相同的方式工作).
我想知道为什么Guava没有这样做,因为他们已经在其他地方使用了这些注释.
标签:java,nullpointerexception,eclipse,guava
来源: https://codeday.me/bug/20190709/1409546.html