修改private的字段分三步:
(1)将你需要你那个private字段对应的Field取出来;
(2)将访问标志,修改为true;
(3)设置对相应的field设置值即可。
(1)将你需要你那个private字段对应的Field取出来;
(2)将访问标志,修改为true;
(3)设置对相应的field设置值即可。
public class Student {
private String name;
private int tall;
public String getName() {
return name;
}
public int getTall() {
return tall;
}
private void setTall(int tall) {
this.tall = Integer.valueOf(tall);
}
}
public class Test {
public static void main(String[] args) {
try {
Field field = Student.class.getDeclaredField("name");
Student student = new Student();
field.setAccessible(true);
field.set(student, "jack");
student.getName();
System.out.println(student.getName());
Method method = Student.class.getDeclaredMeth