Why java classes do not inherit annotations from implemented interfaces?

I'm using a Dependency Injection framework (Guice's AOP to intercept some method calls specifically). My class implements an interface and I would like to annotate the interface methods so the framework could select the right methods. Even if the annotation type is annotated with Inherited annotation implementing class doesn't inherit the annotation as stated in Inherited's java doc:

Note also that this meta-annotation only causes annotations to be inherited from superclasses; annotations on implemented interfaces have no effect.

What could be the reason for this? Getting to know all interfaces that an object's class does implement in runtime is not that hard thing to do so there must be a good reason behind this decision.

67346 次浏览

我想说的原因是,否则就会发生多重继承问题。

例如:

@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()

结果会是什么? “ baz”,“ phleem”还是“ flopp”?


因此,接口上的注释很少有用。

来自 贾瓦多克 for@Heritage:

指示自动继承注释类型。如果 继承的元注释出现在注释类型上 declaration, and the user queries the annotation type on a class 声明,并且类声明对此没有注释 类型,然后将自动查询该类的超类 这个过程会一直重复,直到有一个注释 或类层次结构(对象)的顶部为 如果没有超类对此类型有注释,则 query will indicate that the class in question has no such annotation. 注意,如果注释的 Type 用于对类以外的任何内容进行注释 这个元注释只会导致从 超类; 实现的接口上的注释没有效果。

另一方面,JSR 305验证器执行某种继承查找:

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


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

然后对 Student.getAge()进行有效的验证是 @Nonnull @Min(5)@Nonnull没有 @Inherited元注释。