Multiple Targets and TYPE_USE
What you'll learn: How to allow annotations on multiple element types and use TYPE_USE for comprehensive type annotation coverage.
Combining Multiple Targets
You've seen individual ElementType values, but annotations often need to apply to multiple contexts. You can specify several targets by passing an array to @Target:
@Target({ElementType.METHOD, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface Validated {
String message() default "Invalid";
}
Now @Validated can annotate both methods and fields. This flexibility lets framework developers create versatile annotations without duplicating definitions.
Think of it like: A "No Smoking" sign that applies to both indoor rooms and outdoor patios—one rule, multiple locations.
The Power of TYPE_USE
Introduced in Java 8, ElementType.TYPE_USE is the most comprehensive target. It allows annotations anywhere a type is used:
- Variable declarations:
@NonNull String name - Return types:
@NonNull String getName() - Type parameters:
List<@NonNull String> - Type casts:
(@NonNull String) obj - Array levels:
@NonNull String @NonNull [] - Exception specifications:
throws @Critical IOException
@Target(ElementType.TYPE_USE)
@Retention(RetentionPolicy.RUNTIME)
public @interface NonNull {
}
// Now usable everywhere:
public @NonNull String process(@NonNull String input) {
List<@NonNull String> items = new ArrayList<>();
return (@NonNull String) input.trim();
}
This enables powerful type-checking tools and null-safety analyzers to inspect every type reference in your code.
Combining TYPE_USE with Others
You can combine TYPE_USE with traditional targets for maximum flexibility:
@Target({ElementType.TYPE_USE, ElementType.PARAMETER})
Key takeaway: Use multiple @Target values to make annotations versatile across contexts, and leverage TYPE_USE to annotate types anywhere they appear—enabling sophisticated static analysis and type-safety tools.