Eclipse gives me the warning "Potential null pointer access: The variable ann may be null at this location":
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. 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.
Eclipse e4 has much better support for null checks and resource tracking in the compiler.
Another solution is writing your own version of checkNotNull
like so:
@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).
I'm wondering why Guava doesn't do that since they already use these annotation elsewhere.