2017-01-26 29 views
0

每個註解類型都隱式繼承java.lang.annotation.Annotation接口。Annotation界面的用途是什麼?

package java.lang.annotation; 
public interface Annotation{ 
    boolean equals(Object obj); 
    int hashCode(); 
    String toString(); 
    Class<? extends Annotation> annotationType(); 
} 

但是,註釋不會從Annotation接口繼承任何元素,它是所有註記類型的隱式祖先。所以,如果我下面做,將導致編譯時錯誤

@CustomAnnotation(toString="toStringValue") 

能有人給我解釋一下,然後

是什麼註解接口的目的是什麼?以及它使用的是什麼 ?

+1

從[JLS(9.6.1)](https://docs.oracle.com/javase/specs/jls/se8/html/jls-9.html#jls-9.6.1):「它是如果在註解類型中聲明的任何方法的簽名具有與Object類中或接口java.lang.annotation.Annotation中聲明的任何public或protected方法的簽名相同的簽名,則會出現編譯時錯誤。所以也許這就是這個接口的目的(爲了強制執行) –

回答

3

Annotation是一個接口。這些方法是您的標準接口abstract方法聲明。

你指的是在你的

@CustomAnnotation(toString="toStringValue") 

(使用toString)例如什麼是annotation type element。這是兩件不同的事情。後者是註釋類型的特殊語法。 Annotation不是註釋類型,它是一種接口類型。

Annotation類型提供的是註釋類型的常見超類型。所以,你可以做

Annotation custom = SomeClass.class.getAnnotation(CustomAnnotation.class); 
custom.annotationType(); 

這些方法(equalstoStringhashCode)簡單地重新定義在Annotation接口來指定自己的行爲。它們並不是嚴格要求的,因爲如果Java語言沒有聲明它們,它就隱式地爲adds all those methods to all interface types

+0

註解類型也是一種幾乎沒有限制的接口,其中一個限制是註釋類型之間不允許繼承,那麼創建超類型的意義何在? –

+0

Annotation類型提供的是註釋類型的常見超類型,如果這是唯一目的,爲什麼Annotation不是標記接口?,我很困惑! –

+1

@AmitBhati註釋類型是一種接口類型,但接口類型不一定是註釋類型。它不是標記接口,因爲Java語言想要包含更多的行爲('annotationType'方法)並描述其他3種方法的更具體的行爲。 –