为什么我在这里得到空的注释数组

| 根据文档和答案,我应该在以下代码中使用\“ Override \”(或类似名称):
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 []
我想念什么?     
已邀请:
        因为``2''批注具有``3'',即它没有编译到类文件中,因此在运行时无法通过反射使用。仅在编译期间有用。     
        我写了这个例子来帮助我理解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()));
    }
}
    

要回复问题请先登录注册