Getting value of public static final field/property of a class in Java via reflection

Viet picture Viet · Apr 21, 2010 · Viewed 91.3k times · Source

Say I have a class:

public class R {
    public static final int _1st = 0x334455;
}

How can I get the value of the "_1st" via reflection?

Answer

M. Jessup picture M. Jessup · Apr 21, 2010

First retrieve the field property of the class, then you can retrieve the value. If you know the type you can use one of the get methods with null (for static fields only, in fact with a static field the argument passed to the get method is ignored entirely). Otherwise you can use getType and write an appropriate switch as below:

Field f = R.class.getField("_1st");
Class<?> t = f.getType();
if(t == int.class){
    System.out.println(f.getInt(null));
}else if(t == double.class){
    System.out.println(f.getDouble(null));
}...