Java:如何通过存储在变量中的名称访问类的字段? [英] Java: How can I access a class's field by a name stored in a variable?
本文介绍了Java:如何通过存储在变量中的名称访问类的字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何在名称为动态并存储在字符串变量中的类中设置或获取字段?
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
}
}
推荐答案
您必须使用反射:
- 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
下面是一个处理公共字段的简单情况的例子。如果可能,更好的替代方法是使用属性。
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);
}
}
这篇关于Java:如何通过存储在变量中的名称访问类的字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文