Annotation Inheritance in Java Interfaces
Why don't Java classes inherit annotations from implemented interfaces? This behavior is specifically outlined in the documentation for the @Inherited annotation:
Note also that this meta-annotation only causes annotations to be inherited from superclasses; annotations on implemented interfaces have no effect.
This choice is deliberate, as it prevents a subtle type of multiple inheritance conflict. 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 Flipp { @Baz("flopp") public void doStuff() {} } public class MyClass extends Flipp implements Foo, Bar {}</code>
If annotations from interfaces were inherited, invoking MyClass.class.getMethod("doStuff").getAnnotation(Baz.class).value() would result in an ambiguity:
To avoid this conflict, Java explicitly does not inherit annotations from interfaces. This ensures that the inheritance hierarchy for annotations is clear and consistent.
In cases where interface annotations are desired, it is recommended to explicitly annotate the implementing class methods. This provides the flexibility to control the specific annotations applied to each method.
The above is the detailed content of Why Don\'t Java Classes Inherit Annotations from Implemented Interfaces?. For more information, please follow other related articles on the PHP Chinese website!