Java定义一个Student类并进行封装初始化对象stu包含属性name:张三;age18通过反射的方式将该对象的年龄改成19
以下是定义一个Student类并进行封装,然后使用反射的方式将对象的年龄改成19的Java代码:
import java.lang.reflect.Field;
public class Student {
private String name;
private int age;
public Student(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException {
Student stu = new Student("张三", 18);
System.out.println("修改前的年龄:" + stu.getAge());
// 获取age字段
Field ageField = Student.class.getDeclaredField("age");
// 设置可访问
ageField.setAccessible(true);
// 修改age的值为19
ageField.set(stu, 19);
System.out.println("修改后的年龄:" + stu.getAge());
}
}
输出结果:
修改前的年龄:18
修改后的年龄:19
注意:使用反射修改对象的属性需要将字段设置为可访问,即调用setAccessible(true)方法,否则会抛出IllegalAccessException异常
原文地址: https://www.cveoy.top/t/topic/hGcX 著作权归作者所有。请勿转载和采集!