Here is a Java code, which I have found on the net, to set field value using reflection:
public static boolean setField(Object object, String fieldName, Object fieldValue) {
Class<?> clazz = object.getClass();
while (clazz != null) {
try {
Field field = clazz.getDeclaredField(fieldName);
field.setAccessible(true);
field.set(object, fieldValue);
return true;
} catch (NoSuchFieldException e) {
clazz = clazz.getSuperclass();
} catch (Exception e) {
throw new IllegalStateException(e);
}
}
return false;
}
And it works. So far so good. But now, I am trying to upgrade this code to support setting values of a nested objects. Lets say:
setField(obj, "data.value", 10)
What I have tried:
This is what I have ATM (by no means it is a final version):
public boolean setField(Object object, String fieldName, Object fieldValue) {
String[] fieldChain = fieldName.split(Pattern.quote("."));
Integer current = 0;
Class<?> clazz = object.getClass();
while (clazz != null) {
try {
Field field = clazz.getDeclaredField(fieldChain[current]);
field.setAccessible(true);
if (current < fieldChain.length - 1){
clazz = field.getType();
++current;
} else {
field.set(???, fieldValue);
return true;
}
} catch (NoSuchFieldException e) {
clazz = clazz.getSuperclass();
current = 0;
} catch (Exception e) {
throw new IllegalStateException(e);
}
}
return false;
}
What I do not know, is what should be passed as 1st param of field.set method:
field.set(???, fieldValue);
I cannot pass top level object here - it should be lower level object, but I have no idea how to get it.
I have tried various things, like: clazz, clazz.newInstance(), etc - but of course it does not work.
Would appreciate any help.
Thanks in advance.