xyc
2024-11-05 af97e376db85a53b41c9fe069bd2948b59387e49
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
package com.zt.life.modules.mainPart.utils;
 
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
 
 
public class MaptObjectUtils {
    /**
     * Map转成实体对象
     * @param map map实体对象包含属性
     * @param clazz 实体对象类型
     * @param  flag map的key是下划线(和数据库字段名称一致)命名则为true,key是驼峰命名则为false
     * @return
     */
    public static Object map2Object(Map<String, Object> map, Class<?> clazz, boolean flag) {
        if (map == null) {
            return null;
        }
        Object obj = null;
        try {
            obj = clazz.newInstance();
 
            Field[] fields = obj.getClass().getDeclaredFields();
            for (Field field : fields) {
                int mod = field.getModifiers();
                if (Modifier.isStatic(mod) || Modifier.isFinal(mod)) {
                    continue;
                }
                field.setAccessible(true);
                if (flag)
                    field.set(obj, map.get(HumpToUnderline(field.getName())));
                else
                    field.set(obj, map.get((field.getName())));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return obj;
    }
 
    private static String HumpToUnderline(String name) {
        String regex = "([A-Z])";
        Matcher matcher = Pattern.compile(regex).matcher(name);
        while (matcher.find()) {
            String target = matcher.group();
            name = name.replaceAll(target, "_"+target.toLowerCase());
        }
        return name;
    }
}