Java Reference
In-Depth Information
Making an annotation repeatable
If an annotation has been designed to be repeatable, you can just use it. But if you're providing
annotations for your users, then setup is required to specify that an annotation can be repeated.
There are two steps:
1 . Mark the annotation as @Repeatable.
2 . Provide a container annotation.
Here's how you can make the @Author annotation repeatable:
@Repeatable(Authors.class)
@interface Author { String name(); }
@interface Authors {
Author[] value();
}
As a result, the Book class can be annotated with multiple @Author annotations:
@Author(name="Raoul") @Author(name="Mario") @Author(name="Alan")
class Book{ }
At compile time Book is considered to be annotated by @Authors({ @Author(name= "Raoul"),
@Author(name="Mario"), @Author(name="Alan")}), so you can view this new mechanism as
syntactic sugar around the previous idiom used by Java programmers. Annotations are still
wrapped in a container to ensure behavioral compatibility with legacy reflection methods. The
method getAnnotation(Class<T> annotationClass) in the Java API returns the annotation of
type T for an annotated element. Which annotation should this method return if there are
several annotations of type T?
Without diving into too much detail, the class Class supports a new get-AnnotationsByType
method that facilitates working with repeatable annotations. For example, you can use it as
follows to print all the Author annotations on the Book class:
 
Search WWH ::




Custom Search