2012-11-28 132 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'僅適用於類級別的註釋,而不適用於方法級別的註解。 –