反射之PropertyDescriptor

Posted Hui23117

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了反射之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");

使用 PropertyDescriptor

使用 PropertyDescriptor 可以很方便的获得一个类的属性信息

PropertyDescriptor propertyDescriptor = BeanUtils.getPropertyDescriptor(o.getClass(), propName);

可以很方便的获取get、set方法,方便进行反射相关处理

propertyDescriptor.getReadMethod()
propertyDescriptor.getWriteMethod()

参考示例,根据对象和属性名,获取属性值

private String getObjPropStrVal(Object o, String propName) {
        PropertyDescriptor propertyDescriptor = BeanUtils.getPropertyDescriptor(o.getClass(), propName);
        if (propertyDescriptor != null) {
            Object val = null;
            try {
                val = propertyDescriptor.getReadMethod().invoke(o);
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (val == null) {
                return null;
            } else if (propertyDescriptor.getPropertyType().getName().contains("Date")) {
                String date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format((Date) val);
                if (date.endsWith(" 00:00:00")) {
                    date = date.substring(0, 10);
                }
                return date;
            } else {
                return val.toString();
            }
        }
        return null;
    }

以上是关于反射之PropertyDescriptor的主要内容,如果未能解决你的问题,请参考以下文章

Java重要技术(13)内省之属性描述符PropertyDescriptor

反射找到成员

Java内省详解

通过PropertyDescriptor反映射调用set和get方法

通过PropertyDescriptor反映射调用set和get方法

javaBean内省类javaBeanBeanInfoIntrospectorPropertyDescriptor