How do type annotations (introduced in Java 8, JSR 308) differ from traditional declaration annotations, and what new locations can they target?
Short answer
Traditional annotations (pre-Java 8) could only target declarations (a class, method, field, or parameter as a whole); type annotations (enabled by adding ElementType.TYPE_USE to @Target) can additionally be applied anywhere a type is used syntactically -- including generic type…
Advertisement
AModel answer
Traditional annotations (pre-Java 8) could only target declarations (a class, method, field, or parameter as a whole); type annotations (enabled by adding ElementType.TYPE_USE to @Target) can additionally be applied anywhere a type is used syntactically -- including generic type arguments, array component types, and cast expressions -- enabling more precise static analysis tools (like the Checker Framework) to reason about, for example, nullability of a specific generic type parameter rather than just the field as a whole.
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE_USE)
public @interface NonEmpty { }
// Applies to the List itself
List<@NonEmpty String> names;
// Applies to a cast expression's target type
String s = (@NonEmpty String) someObject;Real-world example
A static analysis tool using type annotations distinguishes between List<@Nullable String> (a list that may contain null elements) and @Nullable List<String> (a list reference itself that may be null but never contains null elements), a level of precision impossible to express with pre-Java-8 declaration-only annotations.
Likely follow-ups
- What specific new syntactic locations does TYPE_USE enable that ElementType.FIELD or ElementType.METHOD don't cover?
- How does the Checker Framework use type annotations to implement pluggable, project-specific type systems?
Related topics