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?
Asked
Active
Viewed 840 times
-1

Morteza Malvandi
- 1,656
- 7
- 30
- 73
-
can you post your code ? so that all can know exact scenario ? – Vishal Gajera Dec 03 '15 at 07:01
-
iterate through all superclasses and add their declared fields until superclass is java.lang.Object – Jörn Buitink Dec 03 '15 at 07:05
-
`Class.getFields()` only get static fields – Morteza Malvandi Dec 03 '15 at 07:06
-
1pleas refer to [here](http://stackoverflow.com/questions/16966629/what-is-the-difference-between-getfields-and-getdeclaredfields-in-java-reflectio) – Roger Dwan Dec 03 '15 at 07:08
2 Answers
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()

guillaume girod-vitouchkina
- 3,061
- 1
- 10
- 26