Search code examples
javaintellij-idea

Prevent IDEA nullability warning when array elements are allowed to be null?


I have this package-info.java at my root package for the project:

/**
 In this project, parameters are assumed to be non-null by default.
 If a parameter may be null, you should annotate it with `@Nullable`.
 This file added to tell IDEA about our nullability approach.
 `ParametersAreNonnullByDefault` specifies this approach, but apparently only
 works at the package level, but DefaultQualifier specifies `Nonnull` for all
 packages underneath.
 */
@DefaultQualifier(Nonnull.class)
@javax.annotation.ParametersAreNonnullByDefault
package kopi.apisvc;

import org.checkerframework.framework.qual.DefaultQualifier;

import javax.annotation.Nonnull;

The following demonstration code is an example of the problem, I do not want to change the behavior of the code, I just want IDEA to not show a warning. I do not want to refactor to using an Optional<>, nor use something like Objects.nonNull() which would change the behavior of the code.

  public static void doSomething(){
    @Nullable String value = null;
    var formattedValue = formatThing("", value);
    System.out.println(formattedValue);
  }

  public static String formatThing(Object... elements){
    // implementation that handles null value array elements properly
  }

IntelliJ IDEA displays a warning saying Passing 'null' argument to parameter annotated as @NotNull when a null value is passed to the formatThing() method. However, this is not a concern because the method is designed to handle null values for its elements.

How do I tell IDEA that the element values of the array are allowed to be null?

Adding @Nullable to the declaration of elements is not a valid answer because:

  • it indicates that the array itself may be null (which is not the intention)
  • it doesn't solve the problem anyway - IDEA still displays the warning.

I do not want to add suppression warnings everywhere I call the method with possible null elements.


Versions

  • Java: 21
  • IntelliJ IDEA: 2023.3.3

Solution

  • Thanks to John Bollinger for putting me on the right track - the trick is to reset the defaults for the method of interest.

    Just for this one method where I want the elements to be nullable, set the @DefaultQualifier to be nullable, then explicitly set the input/output parameters to be non-null:

      @DefaultQualifier(Nullable.class)
      public static @Nonnull String formatThing(@Nonnull Object... elements){
        // implementation that handles null value array elements properly
        return "";
      }