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

查看:13
本文介绍了通过反射在 Java 中获取类的公共静态最终字段/属性的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一堂课:

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

如何通过反射获取_1st"的值?

How can I get the value of the "_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天全站免登陆