Aaron Digulla
Aaron Digulla

Reputation: 328564

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":

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.

Upvotes: 5

Views: 4585

Answers (2)

Aaron Digulla
Aaron Digulla

Reputation: 328564

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.

Upvotes: 1

haylem
haylem

Reputation: 22663

You could stop using 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:

  • adjust compiler warning settings,
  • use SuppressWarnings at method or class level,
  • use a more modern compiler (apparently later versions do not trigger this for simple cases),
  • rewrite your code to work and assign the return value of checkNotNull to ann.

Upvotes: 2

Related Questions