22

我正在尝试使用 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  );

    }
  }
4

3 回答 3

42

您需要使用注解接口上的@Retention 注解将注解指定为运行时注解。

IE

@Retention(RetentionPolicy.RUNTIME)
@interface MyAnnotation{}
于 2009-04-08T05:26:34.383 回答
26

简短的回答:您需要将 @Retention(RetentionPolicy.RUNTIME) 添加到您的注释定义中。

解释:

默认情况下,编译器保留注释。它们在运行时根本不存在。起初这听起来很傻,但是有很多注释只供编译器(@Override)或各种源代码分析器(@Documentation 等)使用。

如果您想像示例中那样通过反射实际使用注释,则需要让 Java 知道您希望它在类文件本身中记下该注释。该注释如下所示:

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

有关更多信息,请查看官方文档1,并特别注意有关 RetentionPolicy 的部分。

于 2009-04-08T05:30:10.460 回答
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  );
    }
}
于 2012-03-12T21:02:38.450 回答