[英]Using Java reflections to get class variables
I have the following class: 我有以下课程:
public final class ClassMap {
public static final Class HELLO = HelloActivity.class;
}
I want to be able to access HelloActivity.class
knowing the string "HELLO"
. 我希望能够知道字符串"HELLO"
来访问HelloActivity.class
。 I've tried the following: 我尝试了以下方法:
Field classField = ClassMap.class.getField("HELLO");
But that returns a Field
object. 但这返回一个Field
对象。 How can I get a Class
object back? 我如何找回Class
对象?
Thanks! 谢谢!
Now that you have the Field
object representing the field, ask for the value, ie call classField.get(Object obj)
. 现在,您已经具有表示该字段的Field
对象,要求输入值,即调用classField.get(Object obj)
。
Since your field is static
, the obj
parameter will be ignored, and you should just give a null
value. 由于您的字段是static
,因此obj
参数将被忽略,您应该只提供一个null
值。 Javadoc says so: Javadoc这样说:
If the underlying field is a static field, the
obj
argument is ignored; 如果基础字段是静态字段,则obj
参数将被忽略; it may be null. 它可以为空。
So, do this: 因此,请执行以下操作:
Field classField = ClassMap.class.getField("HELLO");
Object value = classField.get(null);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.