自建反射修改属性方法:setProperty

方法介绍

  • 可将属性名为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
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值