Having this method:
readAllTypes(Class clazz) {...}
Can I access the static variables of the class?
Having this method:
readAllTypes(Class clazz) {...}
Can I access the static variables of the class?
Yes. Just use Class.getDeclaredFields() (or Class.getDeclaredField(String)) as normal, and to get the values, use the Field.getXyz() methods, passing in null for the obj parameter.
Sample code:
import java.lang.reflect.Field;
class Foo {
public static int bar;
}
class Test {
public static void main(String[] args)
throws IllegalAccessException, NoSuchFieldException {
Field field = Foo.class.getDeclaredField("bar");
System.out.println(field.getInt(null)); // 0
Foo.bar = 10;
System.out.println(field.getInt(null)); // 10
}
}
You can find the field using clazz.getDeclaredFields(), which returns a Field[], or by directly getting the field by name, with clazz.getDeclaredField("myFieldName"). This may throw a NoSuchFieldException.
Once you've done that, you can get the value of the field with field.get(null) if the field represents an object, or with field.getInt(null), field.getDouble(null), etc. if it's a primitive. To check the type of the field, use the getType or getGenericType. These may throw an IllegalAccessException if they're not public, in which case you can use field.setAccessible(true) first. You can also set the fields in the same way if you just replace "get" with "set".