In Java annotations marked as @Inherited will only work when annotating classes:
Note that this meta-annotation type has no effect if the annotated type is used to annotate anything other than a class. Note also that this meta-annotation only causes annotations to be inherited from superclasses; annotations on implemented interfaces have no effect.
So interfaces or methods annotated with an @Inherited annotation will not result in implementing classes/methods to also be annotated with the annotation. The reason for this is most likely, that the compiler would'n know which of the annotations to choose, if there are multiple annotations in the class hierarchy as described here.
Now Java 8 introduced the new annotation @Repeatable. I think it would have been natural to remove the above restrictions for annotations that are both marked as @Inherited and @Repeatable, because the compiler should then be able to add the conflicting annotations to the @Repeatable annotation.
Given the following example:
import java.lang.annotation.Inherited;
import java.lang.annotation.Repeatable;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Inherited
@interface RepeatableAnnotations {
RepeatableAnnotation[] value();
}
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Inherited
@Repeatable(RepeatableAnnotations.class)
@interface RepeatableAnnotation {
String value();
}
@RepeatableAnnotation("A")
interface IntefaceA {}
@RepeatableAnnotation("B")
interface IntefaceB {}
@RepeatableAnnotation("C")
@RepeatableAnnotation("D")
public class TestClass implements IntefaceA, IntefaceB {
public static void main(String[] args) {
for (RepeatableAnnotation a : TestClass.class.getAnnotation(RepeatableAnnotations.class).value()) {
System.out.print(a.value());
}
}
}
I would have hoped the output to be ABCD but it is "just" CD (i.e. @Inherited is working exactly like pre Java 8).
Does anyone know if there was good reason for not removing the @Inherited restrictions regarding interfaces and methods in the case of @Repeatable annotations for Java 8?
Is there any workaround to achieve the ABCD output for the above type hierarchy? (other than using reflection to scan the super interfaces for annotations...)