dimanche 19 février 2017

Java Reflection - Accessing field of a field

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. See the attached picture. enter image description here

Any pointers or help would be highly appreciated.

Thanks





Aucun commentaire:

Enregistrer un commentaire