通过反射获取Java中类的公共静态最终字段/属性的值 [英] Getting value of public static final field/property of a class in Java via reflection

查看:346
本文介绍了通过反射获取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));
}...

这篇关于通过反射获取Java中类的公共静态最终字段/属性的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆