Null-Analysis Annotations and Eclipse IDE

Problem

With JSR-305 a proposal for "Annotations for Software Defect Detection" was published. The most prominent annotations were javax.annotation.Nullable and javax.annotation.Nonnull which are already supported in a lot of static code analysis tools and IDEs. Unfortunately JSR-305 never got included in official Java releases, and is currently in status "dormant". It's unlikely that the JCP process is ever taken up again. So the usage of the namespace javax.annotation is somewhat illegal. Last but not least it's very problematic to use them in Java 9 and up (see this article for details).

Therefore the JSR-305 annotations from the package javax.annotation.* should not be used any longer.

What are the alternatives?

It is recommended to use the Jetbrains Annotations for null-analysis:

org.jetbrains.annotations.Nullable
org.jetbrains.annotations.NotNull

Solution

Maven

In the wcm.io Global Parent POM the Jetbrains Annotations are already defined in the Dependency Management section for convenience. To use them in your project just declare:

<dependency>
  <groupId>org.jetbrains</groupId>
  <artifactId>annotations</artifactId>
  <scope>provided</scope>
</dependency>

For compatibility reasons the Findbugs/Spotbugs annotations are defined there as well. In older versions of the wcm.io Global Parent (up to version 19) they were defined by default as dependency, but this is no longer the case since version 20.

 See details how to declare Findbugs/Spotbugs annotations or JSR-305 annotations in your project

To define Findbugs/Spotbugs annotations (Package edu.umd.cs.findbugs.annotations):

<dependency>
  <groupId>com.github.spotbugs</groupId>
  <artifactId>spotbugs-annotations</artifactId>
  <scope>provided</scope>
</dependency>

To define JSR-305 annotations (Package javax.annotations):

<dependency>
  <groupId>com.google.code.findbugs</groupId>
  <artifactId>jsr305</artifactId>
  <version>3.0.0</version>
  <scope>provided</scope>
</dependency>

Eclipse

In Eclipse the Null-Analysis features is disabled by default. To enable it, you can define in your POM:

<!-- Set to 'enabled' to activate org.eclipse.jdt.core.compiler.annotation.nullanalysis feature in eclipse settings -->
<eclipse.settings.nullanalysis>enabled</eclipse.settings.nullanalysis>

It's disabled by default because in projects that are not prepared to use this, or that are using a mix of thirdparty libraries with varying support for them this settings creates tons of of Eclipse warnings.

If enabled, Eclipse supports multiple alternatives of Nullable Annotations (but primarily uses the Jetbrains Annotations):

  • Jetbrains Annotations
  • Findbugs/Spotbugs Annotations
  • JSR-350 Annotations
  • Eclipse JDT Annotations

See also https://sling.apache.org/documentation/development/null-analysis.html