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

时间:2011-06-23 22:06:42

标签: java reflection annotations

根据docanswer,我应该在以下代码中使用“覆盖”(或类似内容):

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 个答案:

答案 0 :(得分:6)

因为@Override注释具有Retention=SOURCE,即它没有编译到类文件中,因此在运行时不能通过反射获得。它仅在编译期间有用。

答案 1 :(得分:0)

我写这个例子是为了帮助我理解斯卡弗曼的答案。

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