4

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.

Paul Bellora
  • 54,340
  • 18
  • 130
  • 181
Aaron Digulla
  • 321,842
  • 108
  • 597
  • 820

2 Answers2

2

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.
haylem
  • 22,460
  • 3
  • 67
  • 96
  • 2
    I agree that it's a solution but I would prefer one which just changed the code instead of changing the way 20 people are used to work :-) – Aaron Digulla Jun 07 '13 at 07:59
  • 2
    It's funny how people downvote this just because they don't like the first sentence, and discard the valid suggestions following it. And it's still a solution too. – haylem Aug 10 '16 at 16:52
1

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.

Aaron Digulla
  • 321,842
  • 108
  • 597
  • 820