-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?

4
  • can you post your code ? so that all can know exact scenario ? Commented Dec 3, 2015 at 7:01
  • iterate through all superclasses and add their declared fields until superclass is java.lang.Object Commented Dec 3, 2015 at 7:05
  • Class.getFields() only get static fields Commented Dec 3, 2015 at 7:06
  • 1
    pleas refer to here Commented Dec 3, 2015 at 7:08

2 Answers 2

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());
        }
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

You're assuming fields will be public.
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()

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.