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 ); } } 

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

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

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

说明:

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

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

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

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

使用@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 ); } }