java map 转 entity
java Map 对象转换为指定的实体对象的方法
/**
* 将映射转换为列表
* @param sourceMap 源映射
* @param targetClass 模板类型
* @return 目标了下的模块
* @param <T> 数据类型
* @throws Exception
*/
public static <T> T mapToEntity(Map<String, Object> sourceMap, Class<T> targetClass) throws Exception {
// 源映射为空时或目标类型为空时直接返回,不用再做转换。
if (MapUtil.isEmpty(sourceMap) || null == targetClass) {
return null;
}
/**
* 转换为【并发散列映射】,避免并发修改错误。
* Exception in thread "main" java.lang.RuntimeException: java.util.ConcurrentModificationException
*/
ConcurrentHashMap concurrentHashMap = new ConcurrentHashMap(sourceMap);
// 获取键集
Set<String> keySet = concurrentHashMap.keySet();
/**
* 迭代键集
*/
for (String key : keySet) {
// 排查非法的空键。
if (StringUtils.isBlank(key)) {
continue;
}
// 暂存旧键,以备后用。
String oldKey = key;
// 将全部的字母转换为小写,并转换为字符数组。
char [] keyChars = key.toLowerCase().toCharArray();
// 校验键组
if (null != keyChars && 0 < keyChars.length) {
// 新键,存储以驼峰命名法的键。
String newKey = "";
// 迭代键组。
for (int i = 0; i < keyChars.length; i++) {
// 排除首位两个位置的字符
if (0 != i && i < keyChars.length - 1 && '_' == keyChars[i]) {
// 将下划线后面的第一个字符转换为大写。
keyChars[i + 1] = Character.toUpperCase(keyChars[i + 1]);
}
// 拼接新键
newKey += keyChars[i];
}
if (newKey.contains("_")) {
newKey = newKey.replace("_", "");
}
// 插入新键,并移除旧键。新键遵循驼峰命名法。
sourceMap.put(newKey, sourceMap.get(oldKey));
sourceMap.remove(oldKey);
}
}
// 重新获取键集
keySet = sourceMap.keySet();
// 实例化【目标实体】
T targetEntity = targetClass.newInstance();
/**
* 迭代已声明了的字段。
* 这些字段可能尚未初始化,所以需要允许通过反射将这些字段初始化。
*/
for (Field field : targetClass.getDeclaredFields()) {
// 设置允许通过反射操作私有字段
field.setAccessible(true);
/**
* 迭代键集
*/
for (String key : keySet) {
// 排查非法的空键。
if (StringUtils.isBlank(key)) {
continue;
}
// 匹配到了并且是完全相同。
if (field.getName().equals(key)) {
// 为当前字段设置初始值。
field.set(targetEntity, sourceMap.get(key));
}
}
// 包含匹配,不严谨。
/*if (sourceMap.containsKey(field.getName())) {
// 为当前字段设置初始值。
field.set(targetEntity, sourceMap.get(field.getName()));
}*/
}
return targetEntity;
}

浙公网安备 33010602011771号