· software · 1 min read
Java Annotation Inheritance
I ran into an issue recently with Java, where I had two classes, one extending from the other, and an annotation attached to the super class.
I was reflecting to see if I could see the annotation applied, but it was wasn’t there! Here are my findings, and my solution to:
How can your subclasses inherit the super classes annotations?
java.lang.Inherited
public class Main {
public static void main(String ... args) {
A a = new A();
B b = new B();
System.out.println(a.getClass().isAnnotationPresent(Annotation.class));
System.out.println(b.getClass().isAnnotationPresent(Annotation.class));
}
}
@Annotation
class A {}
class B extends A {}
@Retention(RetentionPolicy.RUNTIME)
@Inherited // <- here's the key!
@interface Annotation {}
Console Output:
true
true
If you take out @Inherited
the result would be:
Console Output:
true
false
Share: