Raunak Agarwal
Raunak Agarwal

Reputation: 7228

Java Scanning Class for Annotation using Google Reflections

I am trying to scan the Fields inside the class for my custom Annotation using google reflections. I don't know why but the result is always an empty set.

Test Class

public class AnnotationParser {

    public void parse() {
        String packagename = "com.security.rest.client";

        final Reflections reflections = new Reflections(packagename);

        Set<Field> subTypes = reflections.getFieldsAnnotatedWith(Wire.class);

        for (Field field : subTypes) {
            System.out.println("Class : " + field.getName());
        }

    }

    public static void main(String[] args) {
        new AnnotationParser().parse();
    }

}

Annotated Class

public class AuthenticationClient {

    @Wire
    public KerberosAPI kerberosAPI;
    @Wire
    public KerberosSessionManager kerberosSessionManager;
}

Custom Annotation

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

}

Please let me know if anyother information is required.

Upvotes: 2

Views: 3916

Answers (1)

zapp
zapp

Reputation: 1553

Field annotations are not scanned by default. You should add FieldAnnotationScanner to the list of scanners, something like:

new Reflections("com.security.rest.client", new FieldAnnotationsScanner())

Upvotes: 8

Related Questions