简体   繁体   中英

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.

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.

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM