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?
- Findbugs/Spotbugs introduced their own set of annotations, they are available for years and also well supported in tools. They work well, but have one problem: They are licensed under LGPL 2.1, thus it's not allowed to include them in Open Source projects under the Apache License (e.g. Apache Sling, wcm.io).
http://repo1.maven.org/maven2/com/github/spotbugs/spotbugs-annotations/ - Jetbrains published their own set of annotations, and they are not only supported in IntelliJ but also in a lot of code analysis tools and can be configured in Eclipse as well.
http://repo1.maven.org/maven2/org/jetbrains/annotations/
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.
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
Related articles
See also https://sling.apache.org/documentation/development/null-analysis.html