How to avoid "potential null pointer access" when using Preconditions.checkNotNull ()?

Eclipse gives me the warning "Accessing a potential null pointer: ann variable 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 am using Eclipse 3.7 and Guava . Is there any way to get rid of this warning?

I could use SuppressWarnings("null") , but I would have to attach it to a method which, in my opinion, would be bad.

+4
source share
2 answers

Eclipse e4 has much better support for null checks and resource tracking in the compiler.

Another solution is to write your own version of checkNotNull , for example:

 @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 missed the version of checkNotNull() , which accepts error messages, they work the same way).

I am wondering why Guava does not, as they already use this annotation elsewhere.

0
source

You can stop using Eclipse.

Hey, this is the solution. This may not be the one you need, but it solves the problem and is not a very bad solution.

More seriously, you could:

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

Source: https://habr.com/ru/post/1484792/


All Articles