Map转为JavaBean(支持自动类型转换)

即需要三点:
1.下划线的key转为驼峰
2.字段匹配
3.类型自动转换为JavaBean的类型

具体实现:
1.下划线的key转为驼峰

public class GuavaUtils {
    public static String underscoreToCamel(String underscore) {
        return CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, underscore);
    }

    public static String camelToUnderscore(String camel) {
        return CaseFormat.LOWER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, camel);
    }
}

2.转换为Bean及类型自动转换

public class MapUtils {

    private static final String INTEGER_NAME = "java.lang.Integer";
    private static final String BOOLEAN_NAME = "java.lang.Boolean";
    private static final String LONG_NAME = "java.lang.Long";
    private static final String STRING_NAME = "java.lang.String";
    private static final String BYTE_NAME = "java.lang.Byte";
    private static final String SHORT_NAME = "java.lang.Short";
    private static final String FLOAT_NAME = "java.lang.Float";
    private static final String DOUBLE_NAME = "java.lang.Double";

    /**
     * Map --> JavaBean
     * @param javaBean 实例对象
     * @param map
     * @param isCamel true:map的key是驼峰 false:map的key是下划线
     * @return
     */
    @SuppressWarnings({ "rawtypes","unchecked", "hiding" })
    public static  T map2JavaBean(T javaBean, Map map, boolean isCamel) {
        try {
            // 获取javaBean属性
            BeanInfo beanInfo = Introspector.getBeanInfo(javaBean.getClass());
            // 创建 JavaBean 对象
            Object obj = javaBean.getClass().newInstance();

            PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
            if (Objects.nonNull(propertyDescriptors) && propertyDescriptors.length > 0) {
                // javaBean属性名
                String propertyName = null;
                // javaBean属性值
                Object propertyValue = null;
                for (PropertyDescriptor pd : propertyDescriptors) {
                    String STR = GuavaUtils.camelToUnderscore(pd.getName());
                    propertyName = isCamel ? pd.getName() : GuavaUtils.camelToUnderscore(pd.getName());
                    if (map.containsKey(propertyName)) {
                        propertyValue = get(pd.getPropertyType(), map.get(propertyName));
                        pd.getWriteMethod().invoke(obj, new Object[] { propertyValue });
                    }
                }
                return (T) obj;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    /**
     * 注:不支持char类型
     * @param clz
     * @param obj
     * @param 
     * @return
     */
    public static  T get(Class clz, Object obj) {
        String clzName = clz.getName();
        switch (clzName) {
            case BOOLEAN_NAME :
                return (T) Boolean.valueOf(obj.toString());
            case INTEGER_NAME :
                return (T) Integer.valueOf(obj.toString());
            case LONG_NAME :
                return (T) Long.valueOf(obj.toString());
            case STRING_NAME :
                return (T) String.valueOf(obj.toString());
            case BYTE_NAME :
                return (T) Byte.valueOf(obj.toString());
            case SHORT_NAME :
                return (T) Short.valueOf(obj.toString());
            case FLOAT_NAME :
                return (T) Float.valueOf(obj.toString());
            case DOUBLE_NAME :
                return (T) Double.valueOf(obj.toString());
            default:
                return null;
        }

    }

    /**
     * Map集合对象转化成 JavaBean集合对象
     *
     * @param javaBean JavaBean实例对象
     * @param mapList Map数据集对象
     * @param isCamel true:map的key是驼峰 false:map的key是下划线
     * @return
     */
    @SuppressWarnings({ "rawtypes" })
    public static  List mapList2JavaBeanList(T javaBean, List mapList, boolean isCamel) {
        if(mapList == null || mapList.isEmpty()){
            return null;
        }
        List objectList = new ArrayList();

        T object = null;
        for(Map map : mapList){
            if(Objects.nonNull(map)){
                object = map2JavaBean(javaBean, map, isCamel);
                objectList.add(object);
            }
        }

        return objectList;

    }
}

测试用例:

public class CommonTest {

    @Test
    public void Test() {
        System.out.println(GuavaUtils.underscoreToCamel("test_data"));
        System.out.println(GuavaUtils.camelToUnderscore("testData"));
    }


    @Test
    public void TestMap() {
        Map map = new HashMap<>();
        map.put("ticket_type_lv2", "104004");
        map.put("is_wool_user", "true");
        map.put("user_risk_tags", "薅运费");
        map.put("uid", "1213224343");
        TestDemo testDemo = MapUtils.map2JavaBean(TestDemo.builder().build(), map, false);
        System.out.println("success");
    }
}

你可能感兴趣的:(Java)