You can do this in either of the following two ways:
1. You can have one container annotation i.e. @Authors (which can contain one or more Author annotations)
and 0 or 1 @Author annotation.
2. You can omit the container annotation altogether and have multiple repeatable annotations i.e. have multiple @Author annotations.
You cannot have the container annotation and more than one repeatable annotation ( i.e. @Authors + more than one @Author) because it is explicitly prohibited by the language designers. Section 9.7.5 of JLS says:
It is a compile-time error if, in a declaration context or type context, there are multiple annotations of a repeatable annotation type T and any annotations of the containing annotation type of T.
In your last example, myMethod has one Authors and one Author annotation. i.e. effectively, it has three @Author annotations - bob, charlie, and alice.
You can run the following test program to confirm:
Code: Select all
public class TestClass {
@Authors(value={ @Author("bob"), @Author("charlie")}, team="java")
@Author("alice")
//@Author("dave") //NOT ALLOWED
void someMethod(){ }
public static void main(String[] args) throws Exception {
Class c = annotation.TestClass.class;
Method m = c.getDeclaredMethod("someMethod");
Annotation[] aa = m.getDeclaredAnnotations();
for(Annotation a : aa) System.out.println(a); //This will print two annotations - one Authors and one Author(alice)
Authors containerOfAuthors = m.getDeclaredAnnotation(Authors.class);
Author[] authors = containerOfAuthors.value(); //this has two author annotations - bob and charlie
for(Author a : authors){
System.out.println(a+" id : "+a.id()+" value : "+List.of(a.value()));
}
}
}