Click here to Skip to main content
15,868,141 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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.
Posted
Updated 6-Apr-18 12:16pm

1 solution

No need to reinvent the wheel. You can use Apache commons lang3 for basic reflection utilities and use commons beanutils for more advanced scenarios, like accessing nested properties. See the links below.

FieldUtils (Apache Commons Lang 3.7 API)[^]

org.apache.commons.beanutils (Apache Commons BeanUtils 1.9.2 API)[^]

Java BeanUtils Nested Property Access[^]

Good luck!
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900