Search code examples
javaintellij-ideanullpointerexceptionannotations

How can I apply @Nonnull annotation to everything including type use and type parameters?


I'd like to tell IntelliJ that everything should not be null by default, unless explicitly annotated with @Nullable.

With JSR305 library and the code below, we can partially accomplish it.

import javax.annotation.Nonnull;
import javax.annotation.meta.TypeQualifierDefault;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

@Nonnull
@TypeQualifierDefault({ElementType.FIELD, ElementType.LOCAL_VARIABLE, ElementType.METHOD, ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@interface NonnullByDefault {
}

(See also: https://www.jetbrains.com/help/idea/parametersarenonnullbydefault-annotation.html)

However, currently @Nonnull from JSR305 lacks support for TYPE_USE and TYPE_PARAMETERS, which doesn't allow declarations like var list = new ArrayList<@Nonnull String>();. This gives an error: '@Nonnull' not applicable to type use.

So the above @NonnullByDefault annotation is not working for type use and type parameters even if I include them to TypeQualifierDefault. Are there any way to make them not null without explicit annotations?


Solution

  • As pointed out in that comment by user mernst, using javax.annotation.Nonnull is probably not the best choice.

    Beyond that, I fear that the answer is that IntelliJ doesn't allow for the kind of checking that you intend to use.

    Thus, at this point, the most promising option would be to use said checkerframework.