(Java 21, IntelliJ Idea 2024)
Hello,
I’m new-ish to the Java ecosystem and I can’t seem to find any proper annotation for “not null” that does the job entirely.
Let me explain :
@NonNull
adds an extra runtime check. I don’t want that. I just want a static check at compile time.@CheckForNull
forces the receiver of the value to check for nullability. No thank you. The point is that the sender of the value does not send null in the first place.@NotNull
doesn’t seem to work all the time. Same-class checks are OK, but checks when passing null from another class let null through. (see example below)
Example :
@AllArgsConstructor
@FieldDefaults(makeFinal = true, level = lombok.AccessLevel.PRIVATE)
public class MyClass {
@NotNull SomeOtherClass mMustNotBeNull;
}
...
// in some other class :
final MyClass c = new MyClass(null); // <-- does not even raise a warning !?!
I have checked that the corresponding warnings are activated in IntelliJ, as per @NotNull, @Nonnull etc. all don’t work in IntelliJ IDEA
I am fully aware that @NotNull is only supposed to be an indication, it’s not designed for enforcement. What I want to know is : In 2024, is there any annotation that actually enforces non-nullability at compile time or at least in the IDE, in most cases?