dimanche 14 août 2016

Is field.setAccessible(true) bad practice?

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.

  1. Is this bad practice? Even though it seems to work I cannot help but feel like this violates some crucial OOP principle.

  2. Do I have to turn setAccessible to false once I am done?

  3. Is there a better way to access the object's underlying value by somehow invoking its getter?





Aucun commentaire:

Enregistrer un commentaire