lundi 31 mai 2021

Use nested reflection to iterate an object that contains objects

as from the title I need to iterate an object using reflection. What do I have:

@Getter
@Setter
public static class ObjectA {
     public ObjectB obj;
}

@Getter
@Setter
public static class ObjectB {
     public String value;
}

String pathValueRetrived = "ObjectA.obj.value";

I have to retrieve the value attribute, obviously in a generic way.

Something like:

String[] pathValue = StringUtils.split(pathValueRetrived, ".");
ObjectA objectA = //retrive the object with values
Object iterator;
for(String idxPath : pathValue){
  if(iterator != null)
      iterator = iterator.getClass().getDeclaredField(path);
  else
      iterator = objectA.getClass().getDeclaredField(path);
}

I thank you very much for your help!





Aucun commentaire:

Enregistrer un commentaire