反射之PropertyDescriptor

发布时间 2023-05-26 20:47:07作者: Hui飞的鱼

反射可以为对象的私有属性赋值
java提供了一个类PropertyDescriptor
通过这个类可以为对象的属性赋值

需要进行赋值的对象

@Data
public class TestEntity {
    private String username;
    private String password;
    private Integer age;
    private Boolean sex;
    private String account;
    private String email;
}

PropertyDescriptor的简单使用

//首先获取PropertyDescriptor
//其中构造方法又两个参数
//1. 属性名 2. 类的Class对象
PropertyDescriptor pd = new PropertyDescriptor("username", TestEntity.class);
//获取set方法, writeMethod写入方法,即set方法
Method method = pd.getWriteMethod();

TestEntity entity = new TestEntity();
//通过set方法为属性赋值
//参数: 1.需要进行赋值的对象,2. 值
method.invoke(entity, "haoren");