Java:如何通过存储在变量中的名称访问类的字段?

如何在名称为动态且存储在字符串变量中的类中设置或获取字段?

public class Test { public String a1; public String a2; public Test(String key) { this.key = 'found'; <--- error } } 

你必须使用reflection:

  • 使用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); } } 
 Class actualClass=actual.getClass(); Field f=actualClass.getDeclaredField("name"); 

上面的代码就足够了。

 object.class.getField("foo"); 

不幸的是,上面的代码对我不起作用,因为该类有空字段数组。