package com.heima.reflect;
public class Demo008 {
public static void main(String[] args) throws Exception {
Student s = new Student("张三", 23);
System.out.println(s);
Tool.setProperty(s, "name", "李四");
System.out.println(s);
}
}
class Student {
private String name;
private int age;
public Student() {
super();
}
public Student(String name, int age) {
super();
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Student [name=" + name + ", age=" + age + "]";
}
}
public class Tool {
public static void setProperty(Object obj, String propertyName, Object value) throws Exception{
Class<? extends Object> clazz = obj.getClass();
//防止字段为private时,无法修改字段值的情况
Field field = clazz.getDeclaredField(propertyName);//暴力反射获取字段
field.setAccessible(true);//去除权限
field.set(obj, value);
}
}