mardi 6 octobre 2020

How to get a nested object field name inside a another object using Reflection

I have an object payload which looks as sodataObject(id=1234567, results=[result(value=11, type=WIN, rStatus=OPEN)], name=null, age=22 )

The object structure as follows:

 class DataObject{
   String id
   Set<Result> results = new HashMap
   String status
   String name
   Int age  
}

class result{
   String value
   String type
   String rStatus

}

I want to get the field 'DataObject.result.rStatus' from the object and set as null in the payload. I have been following How to get a nested field but my field I want to change is nested another level down.

So far I have this which works for the first tier of fields in the DataObject but I can't seem to get to the required fields in the Result object:

Class dataObjectClass= dataObject.getClass();
Field field = dataObjectClass.getDeclaredField("rStatus");
//package java.lang;
 @CallerSensitive
    public Field getDeclaredField(String name)
        throws NoSuchFieldException, SecurityException {
        checkMemberAccess(Member.DECLARED, Reflection.getCallerClass(), true);
        Field field = searchFields(privateGetDeclaredFields(false), name);//comes back null here
        if (field == null) {
            throw new NoSuchFieldException(name);
        }
        return field;
    }
            

However the field object is coming back null as it only searches on the first level of fields and doesn't traverse nested objects.

Is there a way I can get the Field for this nested object field or a better method in the java.lang package that can handle this?





Aucun commentaire:

Enregistrer un commentaire