分享

javaBean对象转换为Map

 小清风的doc 2017-12-15
有些业务场景需要对javaBean对象的每个属性转换为key-value的映射结构,避免出现大批量的setter.操作,就想到了用反射来进行处理,列如:

@Component
public class Bean2MapUtil {
    
    final int MAPSIZE = 256;
    
    public <T> Map<String,Object> transferBean2Map(T paramDTO,String... ignoreProperties) {
        if(paramDTO == null) {
            throw new SandBeachException(SandBeachCodeEnum.BEAN_CONVERT_ERROR);
        }
        try {
            Map<String,Object> map = new HashMap<>(MAPSIZE);
            Class<?> dtoClazz = paramDTO.getClass();
            // 内省+反射获取对象的setter/getter
            BeanInfo beanInfo = Introspector.getBeanInfo(dtoClazz);
            PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors();
            List<String> ignoreList = (ignoreProperties != null ? Arrays.asList(ignoreProperties) : null);
            for (PropertyDescriptor pd : pds) {
                String fieldName = pd.getName();
                if(StringUtils.containsIgnoreCase(fieldName, "class")) {
                    continue;
                }
                // 忽略字段
                if(ignoreList != null && ignoreList.contains(fieldName)) {
                    continue;
                }
                Method readMethod = pd.getReadMethod();
                if(readMethod != null) {
                    readMethod.setAccessible(true);
                    Object value = readMethod.invoke(paramDTO);
                    // 必转换字段
                    map.put(fieldName, value);
                }
            }
            
            return map;
        }
        catch (Exception e) {
            throw new SandBeachException(SandBeachCodeEnum.BEAN_CONVERT_ERROR);
        }
    }

}

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多