How do repeatable annotations work in Java (using @Repeatable), and what problem do they solve?
Short answer
Prior to Java 8, applying the same annotation type multiple times to one element wasn't allowed; @Repeatable (introduced in Java 8) lets you define a container annotation holding an array of the repeatable annotation, allowing multiple instances of the same annotation type to be…
Advertisement
AModel answer
Prior to Java 8, applying the same annotation type multiple times to one element wasn't allowed; @Repeatable (introduced in Java 8) lets you define a container annotation holding an array of the repeatable annotation, allowing multiple instances of the same annotation type to be applied to a single element -- the compiler handles the wrapping/unwrapping automatically, letting reflection code retrieve either the individual repeated annotations or the container transparently via getAnnotationsByType().
@Retention(RetentionPolicy.RUNTIME)
@Repeatable(Schedules.class)
public @interface Schedule {
String day();
}
@Retention(RetentionPolicy.RUNTIME)
public @interface Schedules {
Schedule[] value();
}
public class Job {
@Schedule(day = "MONDAY")
@Schedule(day = "FRIDAY")
public void run() { }
}Real-world example
A job scheduling framework lets developers annotate a single method with multiple @Schedule annotations (one per day it should run), using @Repeatable to allow this multi-application syntax cleanly instead of requiring an awkward single annotation with an array-typed element.
Likely follow-ups
- What does the generated container annotation (@Schedules) look like if you don't use @Repeatable and must retrieve multiple annotations manually?
- How does getAnnotationsByType() differ from getAnnotation() when reading repeatable annotations?
Related topics