3

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?

hylowaker
  • 966
  • 2
  • 9
  • 24
  • JSR 305 was abandoned in 2009, so you might want to use [a different `@NonNull` annotation](https://stackoverflow.com/questions/4963300/which-notnull-java-annotation-should-i-use). If you are willing to use a tool beyond the capabilities of IntelliJ, the Nullness Checker makes all type locations [`@NonNull` by default](https://checkerframework.org/manual/#nullness-checker), and it permits [fine-grained control of defaulting](https://checkerframework.org/manual/#effective-qualifier). – mernst Apr 26 '19 at 15:33
  • Great you found the answer helpful. Is there anything I can add to make it also upvote worthy? – GhostCat May 02 '19 at 04:07

1 Answers1

0

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.

GhostCat
  • 137,827
  • 25
  • 176
  • 248