通过反射在 Java 中获取类的公共静态最终字段/属性的值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2685345/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Getting value of public static final field/property of a class in Java via reflection
提问by Viet
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?
如何通过反射获得“_1st”的值?
采纳答案by M. Jessup
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:
首先检索类的字段属性,然后可以检索值。如果您知道类型,您可以使用带有 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));
}...
回答by Yishai
R.class.getField("_1st").get(null);
Exception handling is left as an exercise for the reader.
异常处理留给读者作为练习。
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.
基本上,您通过反射像任何其他字段一样获得该字段,但是当您调用 get 方法时,您会传入一个 null,因为没有实例可以执行。
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.
这适用于所有静态字段,无论它们是最终的。如果该字段不是公开的,则需要先调用setAccessible(true)
它,当然,SecurityManager 必须允许所有这些。
回答by Brian
I was following the same route (looking through the generated R class) and then I had this awful feeling it was probably a function in the Resources class. I was right.
我遵循相同的路线(查看生成的 R 类),然后我有一种可怕的感觉,它可能是 Resources 类中的一个函数。我是对的。
Found this: Resources::getIdentifier
发现这个: Resources::getIdentifier
Thought it might save people some time. Although they say its discouraged in the docs, which is not too surprising.
认为这可能会为人们节省一些时间。尽管他们在文档中表示不鼓励这样做,但这并不奇怪。