2011-08-23 50 views
10

考慮以下代碼:爲什麼不允許接口作爲註釋成員?

@Retention(RetentionPolicy.RUNTIME) 
@Target(ElementType.METHOD) 
public @interface Bar { 
    Foo foo() default FooImpl.FooConstant; 
} 

編譯器錯誤:

annotation value not of an allowable type

如果我用FooImpl替換Foo,則接受代碼。

這種行爲的原因是什麼?

回答

7

If I replace Foo with FooImpl the code is accepted.

我會很驚訝,如果這個編譯,除非FooImpl是一個枚舉。

註釋構件可僅包含以下內容:

  • 原始類型
  • 字符串
  • 類字面
  • 註釋
  • 枚舉項
  • 或1維的任何的陣列以上

It is a compile-time error if the return type of a method declared in an annotation type is any type other than one of the following: one of the primitive types, String, Class and any invocation of Class, an enum type (§8.9), an annotation type, or an array (§10) of one of the preceding types. It is also a compile-time error if any method declared in an annotation type has a signature that is override-equivalent to that of any public or protected method declared in class Object or in the interface annotation.Annotation.

來源:JLS

3

http://java.sun.com/docs/books/jls/third_edition/html/interfaces.html#9.7

註釋構件類型必須是以下之一:原始的,字符串,類,枚舉的任何上述

陣列它是一個編譯時間錯誤,如果元素類型是與ElementValue不相稱。

希望這會有所幫助!

實測值相同的本文檔中,以及:

http://download.oracle.com/javase/1.5.0/docs/guide/language/annotations.html

「返回類型被限制爲原語,字符串,類,枚舉,註解和前述類型的數組」。如上所述,「接口」是不允許的。

+0

我完成了第一句話,第二個似乎是問題。我想知道爲什麼這是不允許的註釋... – soc

+3

@soc *我履行了第一句話*不,你沒有。 '類<?擴展Foo> fooType()'是有效的,'Foo foo()'不是。 –

+0

認爲Foo Foo()是一種方法(只是爲了簡單起見)......我們能否提到接口作爲方法的返回類型? :) – Nik

相關問題