lundi 6 janvier 2020

Access Nested Field using Java Reflection

Suppose that I have several classes in this style:

public class A {
     public B element;
}

public class B {
     public C anotherElement; // where C refers to another type which contains types D, E, F, etc.....
}

I want to iterate over all of the contained sub-classes (not inherited) and get a list of all fields in the nested object tree. However, when I use reflection code like this:

    Field[] myFields = providedObject.getClass().getDeclaredFields();
    for (Field myField : myFields) {
        // do something here?? to access the sub-fields of the class
        // if I print out myField.getName(), I get the element of class A, but I also want to access the anotherElement of class B (without hard-coding the name 'anotherElement', I want a full traversal of all nested fields)
    }

At the 'do something here' step, I want to access the sub-fields of myField, but I don't see anything in the Field api that directly lets me do this. I've tried:

myField.getDeclaringClass().getDeclaredFields() -> this seems to return the same element that we already saw and not the sub-elements

and

myField.getClass().getDeclaredFields() -> this seems to return the fields of the 'Field' class and not my class A or B

So how would I access the nested fields from the reflection api?

Thanks.





Aucun commentaire:

Enregistrer un commentaire