Use nested reflection to iterate an object that contains objects

Viewed 97

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!

1 Answers

You can probably achieve this with recursion:

public static Object getValue(Object target, String path) throws Exception {
    int index = path.indexOf('.');
    // if we don't find a period (.) or the target is null
    // then just return the target
    if (index < 0 || target == null) {
        return target;
    }
    // get the field name
    String field = path.substring(0, index);
    // get hold of the actual field
    Field field = target.getClass().getDeclaredField(field);
    // used if the field is private
    field.trySetAccessible();
    // recursive call
    return getValue(
        field.get(target),        // gets the value of the field, which is the new target
        path.substring(index + 1) // returns the substring after the found index
    );
}

Some notes:

  1. No actual error handling: You may need to implement that yourself, the current solution just throws everything upwards to the caller
  2. No proper input validation: I.e. if the path contains a period at the start or end of the string.
  3. Not tested
Related