Java:如何通过存储在变量中的名称访问类的字段?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2127197/
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
Java: How can I access a class's field by a name stored in a variable?
提问by ufk
How can I set or get a field in a class whose name is dynamic and stored in a string variable?
如何在名称为动态并存储在字符串变量中的类中设置或获取字段?
public class Test {
public String a1;
public String a2;
public Test(String key) {
this.key = 'found'; <--- error
}
}
采纳答案by Jon Skeet
You have to use reflection:
你必须使用反射:
- Use
Class.getField()
to get aField
reference. If it's not public you'll need to callClass.getDeclaredField()
instead - Use
AccessibleObject.setAccessible
to gain access to the field if it's not public - Use
Field.set()
to set the value, or one of the similarly-named methods if it's a primitive
- 使用
Class.getField()
获得Field
的参考。如果它不是公开你需要调用Class.getDeclaredField()
,而不是 - 使用
AccessibleObject.setAccessible
来访问现场,如果它是不公开 Field.set()
用于设置值,如果它是原始值,则使用同名方法之一
Here's an example which deals with the simple case of a public field. A nicer alternative would be to use properties, if possible.
这是一个处理公共字段简单情况的示例。如果可能,更好的选择是使用属性。
import java.lang.reflect.Field;
class DataObject
{
// I don't like public fields; this is *solely*
// to make it easier to demonstrate
public String foo;
}
public class Test
{
public static void main(String[] args)
// Declaring that a method throws Exception is
// likewise usually a bad idea; consider the
// various failure cases carefully
throws Exception
{
Field field = DataObject.class.getField("foo");
DataObject o = new DataObject();
field.set(o, "new value");
System.out.println(o.foo);
}
}
回答by JITHIN_PATHROSE
Class<?> actualClass=actual.getClass();
Field f=actualClass.getDeclaredField("name");
The above code would suffice .
上面的代码就足够了。
object.class.getField("foo");
Unfortunately the above code didn't work for me , since the class had empty field array.
不幸的是,上面的代码对我不起作用,因为该类有空的字段数组。