-1

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?

Morteza Malvandi
  • 1,656
  • 7
  • 30
  • 73

2 Answers2

0

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());
        }
    }
}
Eldar Budagov
  • 312
  • 2
  • 11
0

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()