dimanche 6 mai 2018

How to get value of inner field of an object with reflection?

class TestA {
  private String fieldA;
  private Integer fieldB;
}

class TestB {
  private String fieldC;
  private TestA testA;
}

I have a TestB object. I would like to access values of TestB object via reflection. But TestB class has a field with TestA.

I have field definition. I try to do this:

field.get(object);

But this line throws IllegalAccessException.

If I can do this, I will access the value of field testA.

field.get(object.fieldA)

But with reflection, I have no idea how can I pass fieldA object instead of object. Because object's type is Object and I cannot cast it, everything is generic in the code.

How can I get the value?

Thanks.





Aucun commentaire:

Enregistrer un commentaire