mercredi 19 avril 2017

How can Java reflection be used to get the value of a subclass

I'm using reflection to obtain the value of properties within an object. This works fine, however, I am having issues with obtaining the value of properties with objects of the object.

For example: I have object A that has property of type object B, which has a property of type object C. The value that I want exists on object C.

public class A {
 String name;
 B propertyB;
}
public class B {
 String name;
 C propertyC;
}
public class C {
 String className;
 String valueOfInterest;
}

I have tried to use a recursive method to return all the fields of object A and B, but this has not worked for me. I've also tried using:

getValueOfField("valueOfInterest")

public String getValueOfField(String fieldName)
 A a = new A();
 a.getClass().getSuperclass().getDeclaredField(fieldName);

to find the field that the wanted value would exist in, as suggested in Java reflection: Find fields of a subclass but this throws a NoSuchFieldException.





Aucun commentaire:

Enregistrer un commentaire