guavaandroid-guava

Preconditions checknotnull annotations produce null warnings


The following line

final ProgramObject data =
            Preconditions.checkNotNull(datas.get(name), TEMPLATE, name);

gives a warning in android studio

Warning:(291, 44) Argument 'data.get(name)' might be null

When looking at the source code of Preconditions:

@CanIgnoreReturnValue
@NonNullDecl
public static <T extends Object> T checkNotNull(
  @NonNullDecl T obj, @NullableDecl String errorMessageTemplate, @NullableDecl Object p1) {
if (obj == null) {
  throw new NullPointerException(lenientFormat(errorMessageTemplate, p1));
}
return obj;

}

It looks like the first parameter is not allowed to get null.

Here is the PR connected to it: https://github.com/google/guava/commit/a890c444e55973384d1370b56afe1a02e7db9c3c

So i wonder:

Obviously if i make a null check i suspect that the parameter can be null


Solution

  • The intent of Preconditions.checkNotNull is that it should only be used on variables that you believe can never be null -- and you want to make sure your belief is correct, and have an exception thrown if you were wrong.

    Guava's setup is working as it intended. It may be appropriate for you to suppress the warning.