首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >为什么Reflections.getFieldsAnnotatedWith()不返回任何字段?

为什么Reflections.getFieldsAnnotatedWith()不返回任何字段?
EN

Stack Overflow用户
提问于 2014-01-23 12:43:02
回答 1查看 1.3K关注 0票数 2

我在反思上遇到了一个问题。我试图用Set方法获得字段的Reflections#getFieldsAnnotatedWith,但是当我运行单元测试时,它什么也不返回,有人能告诉我为什么吗?(我正在使用IntelliJ IDE)

这是我正在使用的课程,这是非常基本的。

代码语言:javascript
复制
//The test class run with junit

public class ReflectionTestingTest {

    @Test
    public void test() {
        Reflections ref = new Reflections(AnnotatedClass.class);
        assertEquals(2, ref.getFieldsAnnotatedWith(TestAnnotation.class).size());
        Set<Field> fields = ref.getFieldsAnnotatedWith(TestAnnotation.class);
    }
}

//The class with the annotated fields I want to have in my Set.

public class AnnotatedClass {

    @TestAnnotation
    public int annotatedField1 = 123;

    @TestAnnotation
    public String annotatedField2 = "roar";
}

//And the @interface itself

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

测试失败的消息如下:

代码语言:javascript
复制
junit.framework.AssertionFailedError: 
Expected :2
Actual   :0
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-01-23 12:50:48

您的AnnotatedClass应该使用@TestAnnotation对字段进行注释。然后,代码将返回2

代码语言:javascript
复制
public class AnnotatedClass {

    @TestAnnotation
    public int annotatedField1 = 123;

    @TestAnnotation
    public String annotatedField2 = "roar";

}

现在,要查询字段和方法,您需要在创建Reflections对象时指定扫描器。此外,Reflections的使用应该是:

代码语言:javascript
复制
Reflections ref = new Reflections("<specify package name here>", new FieldAnnotationsScanner());
票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/21308513

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档