我有两个班: Father
和 Child
public class Father implements Serializable, JSONInterface {
private String a_field;
//setter and getter here
}
public class Child extends Father {
//empty class
}
通过反思,我想在 Child
类中设置 a_field
:
Class<?> clazz = Class.forName("Child");
Object cc = clazz.newInstance();
Field f1 = cc.getClass().getField("a_field");
f1.set(cc, "reflecting on life");
String str1 = (String) f1.get(cc.getClass());
System.out.println("field: " + str1);
但我有个例外:
线程“ main”java.lang.NoSuchFieldException: a _ field 中的异常
但如果我尝试:
Child child = new Child();
child.setA_field("123");
很管用。
使用 setter 方法,我遇到了同样的问题:
method = cc.getClass().getMethod("setA_field");
method.invoke(cc, new Object[] { "aaaaaaaaaaaaaa" });