TheDocumentation Index
Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt
Use this file to discover all available pages before exploring further.
@Inherited meta-annotation in Java specifies that an annotation applied to a class is automatically inherited by its subclasses. By default, annotations in Java are not inherited. Applying @Inherited to a custom annotation definition alters this behavior, instructing the JVM’s reflection mechanism to traverse up the class hierarchy to locate the annotation if it is not explicitly present on the queried subclass.
Syntax and Declaration
To create an inherited annotation, applyjava.lang.annotation.Inherited to the annotation declaration. Because inheritance resolution typically occurs dynamically, it is almost always paired with @Retention(RetentionPolicy.RUNTIME).
Technical Mechanics and Limitations
The behavior of@Inherited is strictly governed by the Java Language Specification and operates under specific constraints:
- Class-Level Restriction:
@Inheritedonly affects annotations applied to class declarations (ElementType.TYPE). It has absolutely no effect if the annotation is applied to methods, fields, constructors, or local variables. Subclass methods do not inherit annotations from overridden superclass methods, regardless of the@Inheritedmeta-annotation. - Class Extension vs. Interface Implementation: The inheritance mechanism strictly follows class extension (
extends). It does not apply to interface implementation (implements).- If an interface is annotated with an
@Inheritedannotation, classes that implement that interface will not inherit the annotation. - If a sub-interface extends a super-interface annotated with an
@Inheritedannotation, the sub-interface will not inherit the annotation.
- If an interface is annotated with an
- Reflection Resolution: The inheritance is resolved at runtime via the
java.lang.Classreflection API. WhenClass.getAnnotation(Class<A> annotationClass)is invoked:- The JVM first checks if the annotation is directly present on the target class.
- If absent, and the annotation type is meta-annotated with
@Inherited, the JVM queries the superclass. - This recursive traversal continues up the inheritance tree until the annotation is found or
java.lang.Objectis reached.
Behavior Visualization
The following code demonstrates the strict class-hierarchy resolution of@Inherited:
Annotation Overriding
If a subclass explicitly declares the same annotation that it would otherwise inherit, the subclass’s explicit annotation shadows (overrides) the superclass’s annotation. The reflection API will return the annotation directly present on the subclass, halting the upward traversal of the class hierarchy.Master Java with Deep Grasping Methodology!Learn More





