实体类转map方法

该博客介绍了一种使用Java Introspector和PropertyDescriptor将Bean对象转换为Map的方法。通过反射获取Bean的BeanInfo,然后遍历PropertyDescriptors,过滤掉class属性,调用getter方法获取每个属性的值,并存入Map中。此过程适用于需要将Java Bean对象转化为Map进行操作的场景。
    /**
     * 利用Introspector和PropertyDescriptor:属性描述器  将Bean --> Map
     * @param obj  实体类
     * @return
     */
    public static Map<String, Object> transBean2Map(Object obj) {
        if (obj == null) {
            return null;
        }
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            //利用java反射转为BeanInfo
            BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
            // PropertyDescriptor:属性描述器
            PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
            for (PropertyDescriptor property : propertyDescriptors) {
                String key = property.getName();
                // 过滤class属性
                if (!key.equals("class")) {
                    // 得到property对应的getter方法
                    Method getter = property.getReadMethod();
                    Object value = getter.invoke(obj);

                    map.put(key, value);
                }
            }
        } catch (Exception e) {
            log.error("transBeanMap Error {}" ,e);
        }
        return map;

    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

菜鸟小杰子

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值