I am trying to understand how reflection works with Nested objects:
here is ClassA
public class ClassA {
Integer A;
Integer B;
List<ClassB> C;
public Integer getA() {
return A;
}
public void setA(Integer a) {
A = a;
}
public Integer getB() {
return B;
}
public void setB(Integer b) {
B = b;
}
public List<ClassB> getC() {
return C;
}
public void setC(List<ClassB> c) {
C = c;
}
}
ClassB:
public class ClassB {
int a ;
int b;
public int getA() {
return a;
}
public void setA(int a) {
this.a = a;
}
public int getB() {
return b;
}
public void setB(int b) {
this.b = b;
}
}
And i am trying to access the fields like this:
public static void main(String[] args){
ClassA classA=new ClassA();
Field[] fields =classA.getClass().getDeclaredFields();
for (Field field : fields) {
System.out.println(field.getName());
}
}
Problem: i want to access the fields of ClassB , i am trying to do something like this :
fields[2].getType().getDeclaredFields();
but getType() returns interface java.util.List which is true but i am aiming for the members/fields of ClassB
Then i tried :
fields[2].getGenericType()
which returns java.util.List
and in Debug mode i can see it returns ParameterizedTypeImpl but i am not declare and fetch actualTypeArguments.
Somehow it gives compilation problems when i declare parameterizedTypeImpl.
ParameterizedTypeImpl impl=fields[2].getGenericType();
ParameterizedTypeImpl cannot be resolved to a type
Any pointers or help would be highly appreciated.
UPDATE:
I found the solution :
for (Field field : fields) {
if(field.getType().getTypeName().equalsIgnoreCase("java.util.List")){
ParameterizedType impl=(ParameterizedType) field .getGenericType();
String nameOfClass=impl.getActualTypeArguments()[0].getTypeName();
}
Thanks for your help guys.