[英]How do I avoid “potential null pointer access” when using Preconditions.checkNotNull()?
Eclipse gives me the warning "Potential null pointer access: The variable ann may be null at this location": 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
}
I'm using Eclipse 3.7 and Guava . 我正在使用Eclipse 3.7和Guava 。 Is there a way to get rid of this warning?
有没有办法摆脱这个警告?
I could use SuppressWarnings("null")
but I would have to attach it to the method which I feel would be a bad idea. 我可以使用
SuppressWarnings("null")
但我必须将它附加到我认为不太好的方法。
Eclipse e4 has much better support for null checks and resource tracking in the compiler. Eclipse e4对编译器中的空检查和资源跟踪有更好的支持。
Another solution is writing your own version of checkNotNull
like so: 另一种解决方案是编写自己的
checkNotNull
版本,如下所示:
@Nonnull
public static <T> T checkNotNull(@Nullable T reference) {
if (reference == null) {
throw new NullPointerException();
}
return reference;
}
Now you can use this approach: 现在你可以使用这种方法:
SomeAnnotation ann = Preconditions.checkNotNull( type.getAnnotation( SomeAnnotation.class ) );
(I've omitted the version of checkNotNull()
which take error messages; they work in the same way). (我省略了
checkNotNull()
错误消息的checkNotNull()
版本;它们以相同的方式工作)。
I'm wondering why Guava doesn't do that since they already use these annotation elsewhere. 我想知道为什么Guava没有这样做,因为他们已经在其他地方使用了这些注释。
You could stop using Eclipse. 你可以停止使用Eclipse。
Hey, it's a solution. 嘿,这是一个解决方案。 It may not be the one you want, but it solves the problem and isn't really a bad solution.
它可能不是你想要的那个,但它解决了问题,并不是一个真正糟糕的解决方案。
More seriously, you could: 更严重的是,您可以:
SuppressWarnings
at method or class level, SuppressWarnings
, checkNotNull
to ann
. checkNotNull
的返回值赋给ann
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.