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

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

问题描述

我正在使用依赖注入框架(Guice 的 AOP 专门拦截一些方法调用).我的类实现了一个接口,我想注释接口方法,以便框架可以选择正确的方法.即使注解类型是用Inherited 注释实现类不继承 Inherited's java doc 中所述的注释:

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.

推荐答案

我会说原因是否则会出现多继承问题.

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

结果如何?'baz'、'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天全站免登陆