2011-06-23 48 views
4

按照doc併爲此answer我應該有「越權」(或類似的東西),在下面的代碼:爲什麼我收到的註釋空數組這裏

import java.lang.reflect.*; 
import java.util.*; 
import static java.lang.System.out; 
class Test { 
    @Override 
    public String toString() { 
    return ""; 
    } 
    public static void main(String ... args) { 
    for(Method m : Test.class.getDeclaredMethods()) { 
     out.println(m.getName() + " " + Arrays.toString(m.getDeclaredAnnotations())); 
    } 
    } 
} 

但是,我得到一個空陣列。

$ java Test 
main [] 
toString [] 

我在想什麼?

回答

6

由於@Override註釋具有Retention=SOURCE,即它沒有編譯到類文件中,因此在運行時通過反射不可用。它僅在編譯期間有用。

+0

我實際上正在嘗試'@棄用',並且工作。那麼,什麼時候只爲編譯器識別出「Retention = SOURCE」呢? – OscarRyz

+0

@OscarRyz:'@ Deprecated'具有'Retention = RUNTIME',* *可以使用反射。這些東西都在javadoc中(http://download.oracle.com/javase/6/docs/api/java/lang/Deprecated.html)。 – skaffman

+0

是的,我可以從你的答案中推論出來。我怎樣才能訪問這些信息,我想我可以在編譯階段插入* something *,你能指出我的方向嗎? – OscarRyz

0

我寫了這個例子來幫助我理解skaffman的答案。

import java.lang.annotation.Retention; 
import java.lang.annotation.RetentionPolicy; 
import java.lang.reflect.Method; 
import java.util.Arrays; 

class Test { 

    @Retention(RetentionPolicy.RUNTIME) 
    public @interface Foo { 
    } 

    @Foo 
    public static void main(String... args) throws SecurityException, NoSuchMethodException { 
     final Method mainMethod = Test.class.getDeclaredMethod("main", String[].class); 

     // Prints [@Test.Foo()] 
     System.out.println(Arrays.toString(mainMethod.getAnnotations())); 
    } 
} 
相關問題