Can we use JSR 308 type annotions in Java 7 project (like @NonNull
, ...) ? If yes, what is the related maven dependency ?

- 3,034
- 7
- 33
- 53
2 Answers
Yes... sort of. Type annotations were introduced in Java 8, so they don't work at all in Java 7. And the OpenJDK implementation of JSR 308, for example, is in the OpenJDK 8 JDK. So you can't use that.
But you could use the checker framework which gets around this by allowing you to comment out type annotations in Java 7, but still use them. Setup is described here. You'll need the following maven dependency:
<dependency>
<groupId>org.checkerframework</groupId>
<artifactId>checker</artifactId>
<version>1.9.12</version>
</dependency>

- 2,075
- 16
- 25
-
Thanks. I'll check that. – Aure77 Apr 04 '16 at 12:35
By a "Java 7 project", I assume you mean "a project that can be compiled using a Java 7 compiler". Type annotations are a Java 8 feature -- like lambdas, if you use them, then your code cannot be compiled with a standard Java 7 compiler.
There is a special compiler, the type annotations compiler, that reads type annotations written in comments, like List</*@NonNull*/ String>
. When you compile such a file with a regular Java 7 compiler, that compiler ignores comments. This is how your code can use both type annotations and be compatible with Java 7.
The Checker Framework packages the special compiler together with annotation processors, which warn about incorrect @NonNull
annotations and about possible null pointer exceptions in your code.
You can see its discussion of annotations in comments.
There is Maven integration for the Checker Framework. You'll want to choose the Java 7 directions.

- 7,437
- 30
- 45