I have a abstract class called ClassA in my java project. I extends ClassB from ClassA. Now I want to get all fields of ClassB. When I use ClassB.getDelaredFields(), this method get only classB fields. I can use ClassA.getDeclaredFields() but When I have several hierarchical clasess, I cant use it. I want to get all of fields dymcmically. How?
2 Answers
You can use getFields(), here is example :
public class Generic {
public class SuperA {
public int f0;
}
public class A extends SuperA{
public int f;
}
public class B extends A {
}
public static void main(String[] args) {
Field[] fields = B.class.getFields();
for(Field f: fields) {
System.out.println(f.getName());
}
}
}
1 Comment
Sotirios Delimanolis
You're assuming fields will be
public.public variables (from the class and inherited):
Field[] fields = yourclass.getFields();
every variables non inherited, public and private:
Field[] fields2 = yourclass.getDeclaredFields();
to get the inherited, protected (what can you do with them ?), iterate through superclass
yourclass.getSuperclass()
Class.getFields()only get static fields