Inherited Annotations: Interface Exclusion
Despite the annotation type carrying the Inherited annotation, Java classes do not inherit annotations from implemented interfaces. This behavior stems from potential inheritance conflicts.
Consider the following example:
@Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) @Inherited public @interface Baz { String value(); } interface Foo { @Baz("baz") void doStuff(); } interface Bar { @Baz("phleem") void doStuff(); } class Flipp { @Baz("flopp") public void doStuff() {} } class MyClass extends Flipp implements Foo, Bar {}
When accessing annotations via reflection:
MyClass.class.getMethod("doStuff").getAnnotation(Baz.class).value();
The result becomes ambiguous, as there is no clear inheritance path for the annotation. Would it be "baz," "phleem," or "flopp"?
To avoid such conflicts and maintain clarity, Java intentionally excludes inherited annotations from interfaces. Annotations placed on interface methods typically have limited utility due to this inheritance restriction.
The above is the detailed content of Why Don\'t Java Classes Inherit Annotations from Interfaces?. For more information, please follow other related articles on the PHP Chinese website!