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

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?

111341 次浏览
 R.class.getField("_1st").get(null);

异常处理留给读者作为练习。

Basically you get the field like any other via reflection, but when you call the get method you pass in a null since there is no instance to act on.

This works for all static fields, regardless of their being final. If the field is not public, you need to call setAccessible(true) on it first, and of course the SecurityManager has to allow all of this.

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

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

我沿着同样的路线(查看生成的 R 类) ,然后我有一种可怕的感觉,它可能是 Resources 类中的一个函数。我是对的。

找到了这个: 资源: : getIdentifier

Thought it might save people some time. Although they say its discouraged in the docs, which is not too surprising.

我正在寻找如何得到一个 private静电场,并降落在这里。

对于其他搜索者,以下是方法:

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


class ReflectionHacking {
public static main(String[] args) {
Field field = R.class.getFieldDeclaration("_1st");
field.setAccessible(true);
int privateHidenInt = (Integer)field.get(null);
}
}