我在反思上遇到了一个问题。我试图用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 {}测试失败的消息如下:
junit.framework.AssertionFailedError:
Expected :2
Actual :0发布于 2014-01-23 12:50:48
您的AnnotatedClass应该使用@TestAnnotation对字段进行注释。然后,代码将返回2。
public class AnnotatedClass {
@TestAnnotation
public int annotatedField1 = 123;
@TestAnnotation
public String annotatedField2 = "roar";
}现在,要查询字段和方法,您需要在创建Reflections对象时指定扫描器。此外,Reflections的使用应该是:
Reflections ref = new Reflections("<specify package name here>", new FieldAnnotationsScanner());https://stackoverflow.com/questions/21308513
复制相似问题