lundi 3 juin 2019

Getting the values of the nested fields (fields of the object type field) using Java reflection

There's a class which some of its fields are user-defined objects. I'm going to:

  1. Get the Primary class' fields and traverse through them to get their values.

    1.1 When encountering a field with the type of object, go through this object which has its own fields

  2. Get the values of these nested fields (fields of the object type field)

The problem is at step 2; When I get the fields of the object field, couldn't get their values as I need to pass an object to field.get(object) to indicate which object I want the values of the fields being extracted from, But how can I access the current object of our talking field with the type of object?

Here's the code:

public class PrimaryClass {
    String str;
    int num;
    MyClass cls;
}


PrimaryClass primaryObject = new PrimaryClass();

Field[] primaryObjectFields = primaryObject.getClass().getDeclaredFields();

// ... One of the fields is :  MyClass foo.bar.cls
// Assuming stored with name of clsField 

Field[] myClassObjectFields = clsField.getType().getDeclaredFields();

for (Field f : myClassObjectFields) {

    String fieldValue = f.get(primaryObject /* What to pass here? */); 
    // !!!! The above line Doesn't work since the primary Object doesn't have access to its child's fields

    System.out.println(fieldValue);

}





Aucun commentaire:

Enregistrer un commentaire