Why am I getting an empty array of annotations here
According to the doc and to this answer I should be having "Override" (or something similar) in the following code:
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.getD开发者_JS百科eclaredMethods() ) { 
      out.println( m.getName() + " " + Arrays.toString( m.getDeclaredAnnotations()));
    }
  }
}
But, I'm getting an empty array.
$ java Test
main []
toString []
What am I missing?
Because the @Override annotation has Retention=SOURCE, i.e. it is not compiled into the class files, and is therefore not available at runtime via reflection. It's useful only during compilation.
I wrote this example to help me understand skaffman's answer.
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()));
    }
}
 加载中,请稍侯......
      
精彩评论