[英]How do I avoid “potential null pointer access” when using Preconditions.checkNotNull()?
Eclipse给我警告“潜在空指针访问:变量ann在此位置可能为null”:
SomeAnnotation ann = type.getAnnotation( SomeAnnotation.class );
Preconditions.checkNotNull( ann, "Missing annotation on %s", type );
for( String value : ann.value() ) { // <-- warning happens here
}
我正在使用Eclipse 3.7和Guava 。 有没有办法摆脱这个警告?
我可以使用SuppressWarnings("null")
但我必须将它附加到我认为不太好的方法。
Eclipse e4对编译器中的空检查和资源跟踪有更好的支持。
另一种解决方案是编写自己的checkNotNull
版本,如下所示:
@Nonnull
public static <T> T checkNotNull(@Nullable T reference) {
if (reference == null) {
throw new NullPointerException();
}
return reference;
}
现在你可以使用这种方法:
SomeAnnotation ann = Preconditions.checkNotNull( type.getAnnotation( SomeAnnotation.class ) );
(我省略了checkNotNull()
错误消息的checkNotNull()
版本;它们以相同的方式工作)。
我想知道为什么Guava没有这样做,因为他们已经在其他地方使用了这些注释。
你可以停止使用Eclipse。
嘿,这是一个解决方案。 它可能不是你想要的那个,但它解决了问题,并不是一个真正糟糕的解决方案。
更严重的是,您可以:
SuppressWarnings
, checkNotNull
的返回值赋给ann
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.