I have classes:
ClassA{
public String filedA;
}
ClassB extends ClassA{
public String filedB;
}
ClassC extends ClassB{
public String filedC;
}
Then I create object:
ClassC c=new ClassC();
c.fieldC="TestC";
c.fieldA="TestA";
c.fieldB="TestB";
After I try get all fields, I call
Field[] fields=c.getClass().getDeclaredFields();
But I get array with only one item
fields[fieldC]
How to get all fields from all classes include extends?
Your C class does not extend any class. Then,
getDeclaredFields()
only returnsString filedC
as you have seen. You cannot doc.fieldA="TestA"
andc.fieldB="TestB"
because your class does not declare this fields. Anyway, in case of C extends B and B extends A, method getFields() returns only public fields (including inherited):And getDeclaredFields() returns all fields declared in the class (not including inherited):
Try the following:
If you want all superclass fields, see the following:
Retrieving the inherited attribute names/values using Java Reflection
If you don't want to reinvent the wheel you could rely upon Apache Commons Lang version 3.2+ which provides
FieldUtils.getAllFieldsList
:getDeclaredFields()
which you are using, are not contain inherited flields from superclass.if you want all clields just use
getFields()
methodThis would work with reflection if
ClassC
derived fromClassB
(and presumably fromClassA
etc..). I assume this is a typo ? Then this:would work as expected.
You should be able to get them with
This returns all accessible fields.