Get value of static field from Class
java, reflection, static
Solution
Try with reflection
Steps to follow:
- First retrieve the declared field of the class using its variable name
- Check the type of the returned field
- Then call corresponding method on Field to get the field value
Sample code:
ArrayList<Class<? extends A>> list = new ArrayList<Class<? extends A>>();
list.add(B.class);
list.add(A.class);
// get the value of first class stored in array
Field f = list.get(0).getDeclaredField("i");
Class<?> t = f.getType();
if (t == int.class) {
System.out.println(f.getInt(null));
}
EDIT
As per @Sotirios Delimanolis comments you can get the value directly without checking field type and mathod`Field#getX()` as shown below but it will return `Object` instead of primitive `int`.
Field f = list.get(0).getDeclaredField("i");
System.out.println(f.get(null));
Problem
``` abstract class A { static int i = 5; } class B extends A { static int i = 6; } class C extends A { static int i = 7; } ``` Now I have an `ArrayList<Class<? extends A>>`. How can I get the value of the static field from an `Class<? extends A>`?