首页 > 编程知识 正文

反射修改属性值,通过反射设置属性值

时间:2023-05-06 13:15:22 阅读:254503 作者:3107

方法介绍

可将属性名为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}

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。