方法介绍
可将属性名为propertyName的属性值设置为value class Tool {/**des: 此方法可将属性名为propertyName的属性值设置为value * * @param obj : 相当于学生对象 * @param propertyName : 相当于学生对象的name或者age属性 * @param value :要修改的学生name或age值 * @throws Exception */ public void setProperty(Object obj, String propertyName, Object value) throws Exception { // 获取字节码对象 Class clazz = obj.getClass(); // 暴力反射获取字段 Field f = clazz.getDeclaredField(propertyName); // 取出权限 f.setAccessible(true); // 将属性名为propertyName的属性值设置为value f.set(obj, value); }}方法使用:
class Student { private String name; private int age; public Student() { } public Student(String name, int age) { 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 static void main(String[] args) {Student s = new Student("古力娜扎", 23); System.out.println(s); Tool tool = new Tool(); tool.setProperty(s, "name", "迪丽热巴 "); System.out.println(s);}结果:
student{name='古力娜扎', age=23}student{name='迪丽热巴 ', age=23}