DummyBeginner
DummyBeginner

Reputation: 431

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);

}

When I get the first level field (and set it accessible with setAccessible(true)), To get its inner object field I call these:

topLevelField.getClass().getDeclaredField("details"); 
topLevelField.setAccessible(true);
topLevelField.get(primaryObject);

But couldn't get access to the object field which is instantiated inside the parent object and get this error:

java.lang.IllegalArgumentException: Can not set java.util.List field com.foo.Bar.details to com.foo.Bar

The inner object is a List of objects but could be also non-list objects in some cases.

Upvotes: 3

Views: 2252

Answers (1)

NiNiCkNaMe
NiNiCkNaMe

Reputation: 181

Here is a cool tutorial that can help you get started. in general, get returns you an object, and then you can cast it to what ever type you want. also , you can ask the field for its type ,and the do some logic accordingly to the type of the field . there are also cool methods that is better for you to get familiar with clazz.isAssignableFrom(obj.getClass())

you can read more about it here

Upvotes: 1

Related Questions