您必须使用反射:
- 使用
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); }}


