0
点赞
收藏
分享

微信扫一扫

java中使用反射将javaBean转为map

兽怪海北 2022-03-10 阅读 138
java后端

java中使用反射将javaBean转为map

key : 字段名称
value: 字段值

 //JavaBean转换为Map
    public static Map<String, Object> beanToMap(Object bean) throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();
        Class<?> cl = bean.getClass();
        //获取指定类的BeanInfo 对象
        BeanInfo beanInfo = Introspector.getBeanInfo(cl, Object.class);
        //获取所有的属性描述器
        PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors();
        for (PropertyDescriptor pd : pds) {
            String key = pd.getName();
            Method getter = pd.getReadMethod();
            Object value = getter.invoke(bean);
            map.put(key, value);
        }
        return map;
    }
举报

相关推荐

0 条评论