用反射设置私有字段值 [英] Set private field value with reflection
本文介绍了用反射设置私有字段值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有2个班级: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
:
With reflection I want to set a_field
in Child
class:
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
Exception in thread "main" java.lang.NoSuchFieldException: a_field
但是,如果我尝试:
Child child = new Child();
child.setA_field("123");
有效.
使用setter方法,我有同样的问题:
Using setter method I have same problem:
method = cc.getClass().getMethod("setA_field");
method.invoke(cc, new Object[] { "aaaaaaaaaaaaaa" });
推荐答案
要访问私有字段,您需要将Field::setAccessible
设置为true.您可以离开超类领域.这段代码有效:
To access a private field you need to set Field::setAccessible
to true. You can pull the field off the super class. This code works:
Class<?> clazz = Child.class;
Object cc = clazz.newInstance();
Field f1 = cc.getClass().getSuperclass().getDeclaredField("a_field");
f1.setAccessible(true);
f1.set(cc, "reflecting on life");
String str1 = (String) f1.get(cc);
System.out.println("field: " + str1);
这篇关于用反射设置私有字段值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文