反射getAnnotations()返回null

时间:2013-05-03 13:56:13

标签: java reflection

Searchable.java

@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Searchable { }

Obj.java

public class Obj {
    @Searchable
    String myField;
}

void main(String [] args)

Annotation[] annotations = Obj.class.getDeclaredField("myField").getAnnotations();

我希望annotations包含我的@Searchable。虽然是null。根据文档,这种方法:

  

返回此元素上的所有注释。 (如果此元素没有注释,则返回长度为零的数组。)此方法的调用者可以自由修改返回的数组;它对返回给其他调用者的数组没有影响。

哪个更奇怪(对我而言),因为它返回null而不是Annotation[0]

我在这里做错了什么,更重要的是,我如何才能获得Annotation

4 个答案:

答案 0 :(得分:7)

我刚刚为您测试了这个,它只是起作用:

public class StackOverflowTest {

    @Test
    public void testName() throws Exception {

        Annotation[] annotations = Obj.class.getDeclaredField("myField").getAnnotations();

        System.out.println(annotations[0]);
    }
}

@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@interface Searchable {

}

class Obj {

    @Searchable
    String myField;
}

我跑了它,它产生以下输出:

@nl.jworks.stackoverflow.Searchable()

您可以尝试在IDE中运行上述类吗?我用IntelliJ,openjdk-6尝试了它。

答案 1 :(得分:2)

您的代码是正确的。问题出在其他地方。我只是复制并运行你的代码,它的工作原理。

您可能要在代码中导入错误的Obj类,而您可能需要首先检查该类。

答案 2 :(得分:0)

就我而言,错误出在我自己的注释中。 我修复了几件事,最终结果像这样:

import static java.lang.annotation.ElementType.ANNOTATION_TYPE;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

import java.lang.annotation.Retention;
import java.lang.annotation.Target;
@Target( { METHOD, FIELD, ANNOTATION_TYPE })
@Retention(RUNTIME)
public @interface MyAnnotation{
}

现在可以使用

答案 3 :(得分:0)

就我而言,我忘记添加

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)

方法,所以最后它应该是这样的:

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {
}