mardi 12 décembre 2017

Java reflection on fields from a helper class

I have the following generic function that I would like to use from multiple classes. The problem is that if I call this from a helper class I cannot obtain the field objects because of the visibility.

public <T> List<T> descendingServices(Class<T> cls) {
  List<T> descendings = new ArrayList<>();

  for (Field field : EnvironmentServiceImpl.class.getDeclaredFields()) {
    Object obj;
    try {
      obj = field.get(this);
      if (cls.isInstance(obj)) {
        T descending = (T) obj;
        descendings.add(descending);
      }
    } catch (IllegalAccessException e) {
    }
  }

  return descendings;
}

Can i somehow workaround this without using setAccessible on the field?





Aucun commentaire:

Enregistrer un commentaire