jeudi 14 septembre 2017

Get Annotated Fields for Current Type

I created a @Unique annotation with the intent of annotating fields in my POJOs that make up the unique portions of the class (I use them to build a hash, but that's beyond the scope of my question). To assist with locating fields annotated with @Unique, I'm using the reflections library, but I'm having an issue limiting the results of getFieldsAnnotatedWith() to the fields for the specific type I have an instance of.

Essentially, this is what I have:

public @interface Unique {
}

public class BaseModel {
    @Unique
    private String url;
    @Unique
    private Date myDate;

    public String generateUniqueHash() {
        StringBuilder sb = new StringBuilder();
        ConfigurationBuilder bulder = new ConfigurationBuilder()
            .setUrls(ClasspathHelper.forClass(Unique.class))
            .setScanners(new FieldAnnotationScanner());
        Reflections reflections = new Reflections(builder);
        Set<Field> fields = reflections.getFieldsAnnotatedWith(Unique.class);

        for (Field field : fields) {
            // sb.append(stuff);
        }

        return generateHash(sb.toString());
    }
}

public class MyModel extends BaseModel {
    @Unique
    private String moreStuff;
}

public class AnotherModel extends BaseModel {
    @Unique
    private String evenmoreStuff;
}

Given the above code, if I call anotherModel.generateUniqueHash(), the Set returned by getFieldsAnnotatedWith() will contain fields annotated in the MyModel class, in addition to the fields annotated in AnotherModel. How do I filter fields only annotated by the current instance of a subclass of BaseModel? In other words, in this case, how would I limit to fields in the BaseModel and AnotherModel classes, but ignore the ones in MyModel?





Aucun commentaire:

Enregistrer un commentaire