简体   繁体   中英

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.getDeclaredMethods() ) { 
      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 , ie 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()));
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM