Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/308.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 为什么我在这里得到一个空的注释数组_Java_Reflection_Annotations - Fatal编程技术网

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

Java 为什么我在这里得到一个空的注释数组,java,reflection,annotations,Java,Reflection,Annotations,根据和,我应该在以下代码中使用“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(

根据和,我应该在以下代码中使用“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 []

我缺少什么?

因为注释具有
Retention=SOURCE
,也就是说,它没有编译到类文件中,因此在运行时不能通过反射使用。它只在编译时有用。

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

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

实际上,我正在尝试使用
@Deprecated
,效果很好。因此,当仅为编译器识别is
Retention=SOURCE
时?@OscarRyz:
@Deprecated
具有
Retention=RUNTIME
,并且可以使用反射。这些东西都在javadoc()中。是的,我可以从你的答案中推断出来。我如何访问这些信息,我想我可以在编译阶段插入一些东西,你能给我指出正确的方向吗?@Oscar若要了解某个方法是否被重写,请通过反射查询具有相同签名的超类。@Marcelo,yeap。实际上,我试图在运行时或编译期间获取给定类的所有注释