MyKey_ MyKey_ - 1 year ago 100
Java Question

@Retention of Java type checker annotations

The Java 8 type annotations (JSR 308) allow type checkers to perform static code analysis. For example, The Checker Framework can check for possible nullness via


Various projects define their own NonNull annotations, for example:

  • org.checkerframework.checker.nullness.qual.NonNull

  • edu.umd.cs.findbugs.annotations.NonNull

  • javax.annotation.Nonnull

  • javax.validation.constraints.NotNull

  • lombok.NonNull

  • org.eclipse.jdt.annotation.NonNull

  • etc. (see The Checker Framework Manual, section 3.7)

For such annotations, I would expect the
to have
, because they are usually not needed at runtime. Most importantly, the code does not have any runtime dependencies on the respective library.

follows this approach, most other NonNull annotations, like
(JSR 305) and
itself, have
. Is there any particular reason for the
in these annotations?

Clarification: The Checker Framework supports annotations in comments for backward compatibility. However, using those in Java 8 just to avoid runtime dependencies seems like a dirty hack.

Answer Source

This is a good question.

For the purpose of static checking at compile time, CLASS retention would be sufficient. Note that SOURCE retention would not be sufficient, because of separate compilation: when type-checking a class, the compiler needs to read the annotations on libraries that it uses, and separately-compiled libraries are available to the compiler only as class files.

The annotation designers used RUNTIME retention to permit tools to perform run-time operations. This could include checking the annotations (like an assert statement), type-checking of dynamically-loaded code, checking of casts and instanceof operations, resolving reflection more precisely, and more. Not many such tools exist today, but the annotation designers wanted to accommodate them in the future.

You remarked that with @Retention(RetentionPolicy.CLASS), "the code does not have any runtime dependencies on the respective library." This is actually true with @Retention(RetentionPolicy.RUNTIME), too! See this Stack Overflow question: Why doesn't a missing annotation cause a ClassNotFoundException at runtime? .

In summary, using CLASS retention costs a negligible amount of space at run time, enables more potential uses in the future, and does not introduce a run-time dependency.

In the case of the Checker Framework, it offers run-time tests such as isRegex(String). If your code uses such methods, your code will be dependent on the Checker Framework runtime library (which is smaller than the entire Checker Framework itself).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download