通过反射获取Java中类的公共静态最终字段/属性的值

问题描述:

说我有一个班级:

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

如何通过反射获取字段/属性_1st的值?

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

首先检索类的字段属性,然后可以检索该值。如果您知道类型,则可以使用其中一个带null的get方法(仅对于静态字段,实际上对于静态字段,将完全忽略传递给get方法的参数)。否则你可以使用getType并编写一个适当的开关,如下所示:

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));
}...