In Java I am trying to use reflection to iterate over the declared fields so I can get at the annotations, as well as the underlying value of the field itself:
for(Field field : CustomObject.getClass().getDeclaredFields()) {
field.setAccessible(true);
Object value = field.get(CustomObject);
CustomAnnotation annotation = field.getAnnotation(CustomAnnotation.class);
if (annotation != null) {
//do stuff with annotation and object's value for this field
}
}
In this case the field may be private, which means I cannot access it directly with field.get()
unless I set it as accessible first.
-
Is this bad practice? Even though it seems to work I cannot help but feel like this violates some crucial OOP principle.
-
Do I have to turn
setAccessible
tofalse
once I am done? -
Is there a better way to access the object's underlying value by somehow invoking its getter?
Aucun commentaire:
Enregistrer un commentaire