Java Annotation Inheritance

11 Feb 2015

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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:

1
2
true
true

If you take out @Inherited the result would be:

Console Output:

1
2
true
false

Published on 11 Feb 2015 Find me on Twitter or StackOverflow