There's a class which some of its fields are user-defined objects. I'm going to:
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
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.