Java - Understanding @Inherited meta annotation

[Updated: Jun 23, 2017, Created: Jun 22, 2017]

@Inherited annotation can be used as meta-annotation on the other user defined annotation classes. When such user defined annotations are used on super class, they are automatically inherited to sub classes. Let's understand that we an example.

An annotation without @Inherited

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {
}

An annotation with @Inherited

@Inherited
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface MyInheritedAnnotation {
}

Our example classes

Let's use both above annotation on a super class:

@MyAnnotation
@MyInheritedAnnotation
public class BaseClass {
}
public class SubClass extends BaseClass {
}

The main method

Let's use reflection to get the annotations on the sub class.

public class ExampleMain {
  public static void main(String[] args) {
      MyAnnotation ma = SubClass.class.getAnnotation(MyAnnotation.class);
      System.out.println(ma);

      MyInheritedAnnotation ma2 = SubClass.class.getAnnotation(MyInheritedAnnotation.class);
      System.out.println(ma2);
  }
}

Output

null
@com.logicbig.example.MyInheritedAnnotation()

Limitation

This meta-annotation only causes annotations to be inherited from superclasses; annotations on implemented interfaces have no effect. Also it doesn't work on anything else than a class, i.e. it doesn't work on methods, constructors, fields etc.

Example Project

Dependencies and Technologies Used :

  • JDK 1.8
  • Maven 3.3.9

Inherited Meta Annotation Example Select All Download
  • inherited-meta-annotation
    • src
      • main
        • java
          • com
            • logicbig
              • example

See Also