反射之PropertyDescriptor

反射可以为对象的私有属性赋值
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");
posted @   Hui飞的鱼  阅读(69)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
点击右上角即可分享
微信分享提示