1. The Container Annotation
The container annotation must declare avalue() element whose return type is an array of the repeatable annotation type.
2. The Repeatable Annotation
The annotation to be repeated must be meta-annotated with@java.lang.annotation.Repeatable. The value passed to @Repeatable is the .class literal of the container annotation.
3. Application Syntax
Once linked via the@Repeatable meta-annotation, the compiler allows the annotation to be stacked directly on a target element.
@Configs({@Config(key="timeout", value="5000"), @Config(key="retries", value="3")})
Reflection and Retrieval
Because the compiler wraps repeatable annotations inside the container annotation, Java 8 introduced thegetAnnotationsByType() method in the Reflection API (java.lang.reflect.AnnotatedElement). This method automatically unpacks the container and returns an array of the repeated annotations.
getAnnotation(Config.class) method on an element with repeated annotations, it will return null because the element is technically annotated with the container (@Configs), not the individual @Config annotation.
Structural Constraints
To successfully compile a repeatable annotation, the Java compiler enforces strict rules regarding meta-annotations:- Target Compatibility: The
@Targetof the container annotation must be a subset of, or identical to, the@Targetof the repeatable annotation. If the container annotation can be applied to aMETHOD, the repeatable annotation must also be applicable to aMETHOD. - Retention Compatibility: The
@Retentionpolicy of the container annotation must be equal to or broader than the retention policy of the repeatable annotation. You cannot have aRUNTIMErepeatable annotation wrapped in aSOURCEcontainer annotation. - Documented/Inherited: If the repeatable annotation is marked with
@Documentedor@Inherited, the container annotation must also be marked with the exact same meta-annotations to preserve expected behavior.
Tired of Poor Java Skills? Fix That With Deep Grasping!Learn More





