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

Ora*_*tus 2 java reflection unit-testing annotations reflections

我遇到了一个问题的思考.我正在尝试Set使用Reflections#getFieldsAnnotatedWith方法得到一个字段,但是当我运行单元测试时,它什么也没有返回,有人可以告诉我为什么吗?(我正在使用IntelliJ IDE)

这是我正在使用的课程,这是非常基础的.

//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 {}
Run Code Online (Sandbox Code Playgroud)

测试失败,并显示以下消息:

junit.framework.AssertionFailedError: 
Expected :2
Actual   :0
Run Code Online (Sandbox Code Playgroud)

sad*_*dhu 5

AnnotatedClass应该有字段注释@TestAnnotation.您的代码将返回2.

public class AnnotatedClass {

    @TestAnnotation
    public int annotatedField1 = 123;

    @TestAnnotation
    public String annotatedField2 = "roar";

}
Run Code Online (Sandbox Code Playgroud)

现在,要查询字段和方法,您需要在创建Reflections对象时指定扫描程序.而且,用法Reflections应该是:

Reflections ref = new Reflections("<specify package name here>", new FieldAnnotationsScanner());
Run Code Online (Sandbox Code Playgroud)