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 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; } }