
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:
- Should the @Baz annotation from Foo be inherited?
- Or should the @Baz annotation from Bar be inherited?
- Or should the @Baz annotation from the Flipp superclass be inherited?
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Zend Studio 13.0.1
Powerful PHP integrated development environment

WebStorm Mac version
Useful JavaScript development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Dreamweaver Mac version
Visual web development tools





