如何在名称为动态并存储在字符串变量中的类中设置或获取字段?
public class Test { public String a1; public String a2; public Test(String key) { this.key = 'found'; <--- error } }
您必须使用反射:
Class.getField()
Field
Class.getDeclaredField()
AccessibleObject.setAccessible
Field.set()
这是一个处理公共领域简单案例的示例。如果可能的话,更好的选择是使用属性。
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); } }