2012-11-28 171 views
2

我最近已经开始寻找到Java Web服务,发现以下令人费解:Java的继承注解在接口

如果非要在其中有一个@Consumes注释,然后我实现接口接口中定义的方法中,服务正常工作,就好像@Consumes是继承的。

但是,从阅读各种文章和here,它似乎注释不被继承。

我敲了下面的测试来检查了这一点:

interface ITestAnnotationInheritance { 
    @Consumes 
    void test(); 
} 

class TestAnnotationInheritanceImpl implements ITestAnnotationInheritance { 
    @Override 
    //@Consumes  // This doesn't appear to be inherited from interface 
    public void test() {} 

    public static void main(String[] args) throws SecurityException, NoSuchMethodException { 
     System.out.println(TestAnnotationInheritanceImpl.class.getMethod("test").getAnnotation(Consumes.class)); 
    } 
} 

,其结果是:

null 

如果我取消了@Consumes在TestAnnotationInheritanceImpl类是输出为:

@javax.ws.rs.Consumes(value=[*/*]) 

这证明注释不是被继承的,但是Web服务如何实现w orks罚款?

非常感谢

回答

2

假设你正在谈论关于方法的Web服务注解,那么框架可能使用反射来找到该声明的方法的注释中的超...甚至通过继承层次追了寻找具有相同签名的已实施或重写方法上声明的注释。 (你可以大概判断出究竟是通过查看框架的源代码怎么回事......)


尝试你的榜样的这种变化:

class TestAnnotationInheritance { 
    @Consumes 
    public void test() {} 
} 

class TestAnnotationInheritance2 extends TestAnnotationInheritance { 
    public static void main(String[] args) 
    throws SecurityException, NoSuchMethodException { 
     System.out.println(TestAnnotationInheritance2.class.getMethod("test"). 
          getAnnotation(Consumes.class)); 
    } 
} 

我认为这将表明,该方法中存在注释。 (这里的区别是,我们不重写具有@Consumes注释与另一声明,没有它的方法声明。)


注意,在类注释不正常继承,但他们如果他们被声明为@Inherited注释;见JLS 9.6.3.3javadoc

国际海事组织,注解的继承概念是有点橡胶。但幸运的是,它不会影响核心Java类型系统和计算模型。

+0

'@ Inherited'仅适用于类级别的注释,而不适用于方法级别的注解。 –