Java注释不起作用

Rex*_*ung 20 java annotations

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

    }
  }
Run Code Online (Sandbox Code Playgroud)

Jam*_*ies 37

您需要使用注释界面上的@Retention注释将注释指定为运行时注释.

@Retention(RetentionPolicy.RUNTIME)
@interface MyAnnotation{}
Run Code Online (Sandbox Code Playgroud)


Bra*_*ugh 24

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

说明:

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

如果您想通过反射实际使用注释,就像在您的示例中一样,您需要让Java知道您希望它在类文件本身中记录该注释.那个说明看起来像这样:

@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation{}
Run Code Online (Sandbox Code Playgroud)

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