Why am I getting an empty annotation array 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.getDeclaredMethods() ) { out.println( m.getName() + " " + Arrays.toString( m.getDeclaredAnnotations())); } } } 

But I get an empty array.

 $ java Test main [] toString [] 

What am I missing?

+4
source share
2 answers

Since the @Override annotation has Retention=SOURCE , that is, it does not compile into class files and therefore is not available at run time through reflection. It is only useful at compile time.

+6
source

I wrote this example to help understand how a scuffman responds.

 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())); } } 
0
source

All Articles