Search code examples
javaunit-testingreflectionannotationsreflections

Why doesn't Reflections.getFieldsAnnotatedWith() return any fields?


I'm running into a problem with Reflections. I'm trying to get a Set of fields with Reflections#getFieldsAnnotatedWith method but when I run a unit test, it return nothing, can anybody tell me why? (I'm using the IntelliJ IDE)

Here are the classes I'm using, it's very basic.

//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 {}

The test fails with the following message:

junit.framework.AssertionFailedError: 
Expected :2
Actual   :0

Solution

  • Your AnnotatedClass should have the fields annotated with @TestAnnotation. Your code will return 2 then.

    public class AnnotatedClass {
    
        @TestAnnotation
        public int annotatedField1 = 123;
    
        @TestAnnotation
        public String annotatedField2 = "roar";
    
    }
    

    Now, to query fields and methods, you need to specify the scanner while creating a Reflections object. Moreover, the usage of Reflections should be:

    Reflections ref = new Reflections("<specify package name here>", new FieldAnnotationsScanner());