Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why java classes do not inherit annotations from implemented interfaces?

People also ask

Are annotations inherited from interface Java?

Because there is no multiple inheritance in Java, annotations on interfaces cannot be inherited.

Is implementing an interface inheritance?

Interface inheritance and interface implementation are not the same thing. A class implements an interface by declaring that it implements an interface and then containing the required members to to implement that interface. Interface inheritance refers to an interface inheriting from one or more other interfaces.

Can an annotation implement an interface?

no, there isn't.

Can we annotate interface in Java?

Annotation is defined like a ordinary Java interface, but with an '@' preceding the interface keyword (i.e., @interface ). You can declare methods inside an annotation definition (just like declaring abstract method inside an interface). These methods are called elements instead.


I'd say the reason is that otherwise a multiple-inheritance problem would occur.

Example:

@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{}

If I do this:

MyClass.class.getMethod("doStuff").getAnnotation(Baz.class).value()

what's the result going to be? 'baz', 'phleem' or 'flopp'?


For this reason, annotations on interfaces are rarely useful.


From the Javadoc for @Inherited:

Indicates that an annotation type is automatically inherited. If an Inherited meta-annotation is present on an annotation type declaration, and the user queries the annotation type on a class declaration, and the class declaration has no annotation for this type, then the class's superclass will automatically be queried for the annotation type. This process will be repeated until an annotation for this type is found, or the top of the class hierarchy (Object) is reached. If no superclass has an annotation for this type, then the query will indicate that the class in question has no such annotation. Note that this meta-annotation type has no effect if the annotated type is used to annotate anything other than a class. Note also that this meta-annotation only causes annotations to be inherited from superclasses; annotations on implemented interfaces have no effect.

On the other hand, JSR 305 validators do some sort of inheritance lookup. If you have a hierarchy of classes:

//Person.java
@Nonnull
 public Integer getAge() {...}

//Student.java (inherits from Person)
@Min(5)
public Integer getAge() {...}

Then the effective validations on Student.getAge() are @Nonnull @Min(5). @Nonnull has no @Inherited meta-annotation.