Explain Codes LogoExplain Codes Logo

Which @NotNull Java annotation should I use?

java
null-pointer-exception
annotations
best-practices
Nikita BarsukovbyNikita Barsukov·Sep 2, 2024
TLDR

For optimal compatibility, choose the javax.validation.constraints.NotNull annotation from JSR 380.

// And null shall Not pass! (Gandalf would be proud) @NotNull private String fieldName;

This annotation is the industry standard for verifying that your fields aren't null, recognised by an assortment of Java frameworks and tools.

Understanding compatibility issues

When Compatibility Matters

Choose the javax.validation.constraints.NotNull annotation for a versatile, virtually universal solution without any extra dependencies. Android developers can opt for the androidx.annotation.NonNull annotation that integrates smoothly with lint checks in Android Studio.

When using IDE-specific annotations

If you are using IntelliJ IDEA, then the org.jetbrains.annotations.NotNull annotation is a good choice, as it is designed to work synergistically with the IDE's strong analysis features. For Eclipse users, javax.validation.constraints.NotNull will suffice being supported natively.

When using framework-specific annotations

Framework specific annotations are also something to consider. For instance, Hibernate favours the javax.validation.constraints.NotNull as part of the default JSR 380 specification.

When using checker frameworks

The Checker Framework proposes its own annotations like org.checkerframework.checker.nullness.qual.NonNull, which serves the purpose of both compile-time and runtime checks. It also introduces NNEL (Non-Null Except Locals) which helps reducing verbosity in your code.

Future-proofing your choice

Checking for Standard updates

Stay updated with JSR-related news (305 and 308) as Java standards are always evolving. A new standardized @NotNull could be on the cards.

Making use of static analysis tools

Annotations like edu.umd.cs.findbugs.annotations.NonNull are beneficial for tools like FindBugs, helping early detection of potential bugs.

Updating your IDE

Always keep an eye out for updates in your IDE. As newer versions roll out, they can extend support for different annotations or introduce their own.

Making the right annotation choice

Enhancing readability

The chosen annotation should enhance code readability and avoid common mistakes. Near the top of the list of such mistakes is NullPointerException.

Using Stub strategy

Incorporating Checker Framework can be done without overhead by using stub files which will ensure that code remains reusable and does not get cluttered.