Annotation Inheritance in Java Interfaces
Annotation inheritance, denoted by the @Inherited annotation, allows annotations to be propagated from superclasses to subclasses. However, a notable exception to this rule is that annotations on implemented interfaces are not inherited by implementing classes.
As per the documentation for @Inherited, "this meta-annotation only causes annotations to be inherited from superclasses; annotations on implemented interfaces have no effect."
Reasoning Behind Non-Inheritance
This design decision prevents inheritance conflicts in scenarios where a class implements multiple interfaces with the same conflicting annotation. Consider the following example:
<code class="java">@Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) @Inherited public @interface Baz { String value(); } public interface Foo{ @Baz("baz") void doStuff(); } public interface Bar{ @Baz("phleem") void doStuff(); } public class MyClass implements Foo, Bar{}</code>
If annotations were inherited from interfaces, which @Baz value would be associated with MyClass.doStuff() method? "baz", "phleem", or something else?
Practical Implications
Annotation inheritance on interfaces is generally considered uncommon and impractical due to the potential for conflicts and the difficulty in determining the rightful annotation when multiple interfaces specify conflicting annotations. It is advisable to rely on annotations on superclasses or to use alternative mechanisms for method interception in dependency injection frameworks.
The above is the detailed content of Why Don\'t Java Interfaces Inherit Annotations?. For more information, please follow other related articles on the PHP Chinese website!