@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);
}
} Outputnull @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 ProjectDependencies and Technologies Used:
|