2009-04-08 187 views
18

我正在嘗試使用Java註釋,但似乎無法讓我的代碼識別出存在。 我在做什麼錯?Java註釋不起作用

import java.lang.reflect.*; 
    import java.lang.annotation.*; 

    @interface MyAnnotation{} 


    public class FooTest 
    { 
    @MyAnnotation 
    public void doFoo() 
    {  
    } 

    public static void main(String[] args) throws Exception 
    {    
     Method method = FooTest.class.getMethod("doFoo"); 

     Annotation[] annotations = method.getAnnotations(); 
     for(Annotation annotation : method.getAnnotations()) 
      System.out.println("Annotation: " + annotation ); 

    } 
    } 
+0

您可能想要編輯代碼以刪除未使用的'annotations'局部變量或使用:for(Annotation annotation:annotations){... – blank 2009-04-08 06:13:16

回答

34

您需要在批註界面上使用@Retention批註指定批註作爲運行時批註。

@Retention(RetentionPolicy.RUNTIME) 
@interface MyAnnotation{} 
23

簡短的回答:你需要@Retention(RetentionPolicy.RUNTIME)添加到您的註釋定義。

說明:

註釋是默認由編譯器保存。它們在運行時根本不存在。這聽起來可能聽起來很愚蠢,但有很多註釋只被編譯器(@Override)或各種源代碼分析器(@Documentation等)使用。

如果您想要通過反射(如您的示例)實際使用註釋,則需要讓Java知道您希望它在類文件本身中記錄該註釋。該說明是這樣的:

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

欲瞭解更多信息,請參閱官方文檔1,尤其注意有關的RetentionPolicy位。

3

使用@Retention(RetentionPolicy.RUNTIME) 檢查下面的代碼。它正在爲我工​​作:

import java.lang.reflect.*; 
import java.lang.annotation.*; 

@Retention(RetentionPolicy.RUNTIME) 
@interface MyAnnotation1{} 

@Retention(RetentionPolicy.RUNTIME) 
@interface MyAnnotation2{} 

public class FooTest { 
    @MyAnnotation1 
    public void doFoo() { 
    } 

    @MyAnnotation2 
    public void doFooo() { 
    } 

    public static void main(String[] args) throws Exception { 
     Method method = FooTest.class.getMethod("doFoo"); 
     for(Annotation annotation : method.getAnnotations()) 
      System.out.println("Annotation: " + annotation ); 

     method = FooTest.class.getMethod("doFooo"); 
     for(Annotation annotation : method.getAnnotations()) 
      System.out.println("Annotation: " + annotation ); 
    } 
}