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>?
Try with reflection
Steps to follow:
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)); } As per @Sotirios Delimanolis comments you can get the value directly without checking field type and mathodField#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)); getDeclaredField() I tried with getField() first but that access only public member of the class.Class<?> t = f.getType(); if (t == int.class) do? Is it required?f.getInt() or f.getDouble() methods are called.i is an int? So can I just get rid of that?Field#get(..), you don't have to go through getX where X is a primitive type.
Class? UsegetDeclaredField.