为什么java类不继承实现的接口注解? [英] Why java classes do not inherit annotations from implemented interfaces?

查看:2435
本文介绍了为什么java类不继承实现的接口注解?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在使用Guice的AOP拦截一些方法调用。我的类实现一个接口,我想注释的接口方法,所以吉斯可以选择正确的方法。即使注释类型都标注有<一个href=\"http://download.oracle.com/javase/6/docs/api/java/lang/annotation/Inherited.html\">Inherited注释实现类没有继承注解在继承的Java文档声明:

I've been using Guice's AOP to intercept some method calls. My class implements an interface and I would like to annotate the interface methods so Guice 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.

推荐答案

我说的理由是,否则会出现多重继承的问题。

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

示例:

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

如果我这样做:

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

有什么结果将是什么? 巴兹,phleem'或'flopp?

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

由于这个原因,在接口上注解是很少有用。

For this reason, annotations on interfaces are rarely useful.

这篇关于为什么java类不继承实现的接口注解?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆