lundi 30 mai 2016

How to check if a field has an annotation when using reflection

I'm using reflection so I can check if some fields in another class have annotations.

DummyUser class:

package com.reflec.models;

public class DummyUser {

@NotNull
private String firstName;

private String lastName;

@NotNull
private String email;

public DummyUser() {

}

public DummyUser(String firstName, String lastName, String email) {
    this.firstName = firstName;
    this.lastName = lastName;
    this.email = email;
}

Main class:

public static void main(String[] args) {
    DummyUser user = new DummyUser();

    List<Field> list = seekFieldsWithAnnotations(user);         
    System.out.println("Size: " + list.size());
}

public static List<Field> seekFieldsWithAnnotations(Object o) {
    Class<?> clss = o.getClass();
    List<Field> fieldsWithAnnotations = new ArrayList<>();

    List<Field> allFields = new ArrayList<>(Arrays.asList(clss.getDeclaredFields()));
    for(final Field field : allFields ) {
        if(field.isAnnotationPresent((Class<? extends Annotation>) clss)) {
            Annotation annotInstance = field.getAnnotation((Class<? extends Annotation>) clss);
            if(annotInstance.annotationType().isAnnotation()) {
                fieldsWithAnnotations.add(field);
            }
        }
    }
    //clss =  clss.getSuperclass();
    return fieldsWithAnnotations;
}

If I get the size of the list that is returned by seekFieldsWithAnnotations, the size is always 0. When actually I was expecting it to be 2 because the fields firstName and email have annotations above them.

If I return the allFields list and get its size I get back 3 because there are three fields in the DummyUser class.

So I think the place where I am going wrong is

for(final Field field : allFields ) {
    // Here I am trying to check if annotations are present
    if(field.isAnnotationPresent((Class<? extends Annotation>) clss)) {
        Annotation annotInstance = field.getAnnotation((Class<? extends Annotation>) clss);
        if(annotInstance.annotationType().isAnnotation()) {
            fieldsWithAnnotations.add(field);
        }
    }
}





Aucun commentaire:

Enregistrer un commentaire