Map集合转换成实体类对象,实体类对象转换为map集合,互转工具类
注 : 2019-06-16日 增加第六节 map与实体互转工具类,直接看第6节;
1.调用这个方法BeanMapUtils.mapToBean(),实现map集合转实体类对象;
注意: 这个方法转换时我这边老是报类型转换错误,引用这段代码没有报错的小伙伴可继续使用,此方法扩展性好,报错的小伙伴请看最下面的一个map转实体类对象方法;
//1.通过map构造permission对象
Permission perm = BeanMapUtils.mapToBean(map,Permission.class);
2.工具类
package com.ihrm.common.utils;
import org.springframework.cglib.beans.BeanMap;
import java.util.HashMap;
import java.util.Map;
public class BeanMapUtils {
/**
* 将对象属性转化为map结合
*/
public static <T> Map<String, Object> beanToMap(T bean) {
Map<String, Object> map = new HashMap<>();
if (bean != null) {
BeanMap beanMap = BeanMap.create(bean);
for (Object key : beanMap.keySet()) {
map.put(key+"", beanMap.get(key));
}
}
return map;
}
/**
* 将map集合中的数据转化为指定对象的同名属性中
*/
public static <T> T mapToBean(Map<String, Object> map,Class<T> clazz) throws Exception {
T bean = clazz.newInstance();
BeanMap beanMap = BeanMap.create(bean);
beanMap.putAll(map);
return bean;
}
}
3.BeanMap 内置工具类
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//
package org.springframework.cglib.beans;
import java.security.ProtectionDomain;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.springframework.asm.ClassVisitor;
import org.springframework.cglib.core.AbstractClassGenerator;
import org.springframework.cglib.core.KeyFactory;
import org.springframework.cglib.core.ReflectUtils;
import org.springframework.cglib.core.AbstractClassGenerator.Source;
public abstract class BeanMap implements Map {
public static final int REQUIRE_GETTER = 1;
public static final int REQUIRE_SETTER = 2;
protected Object bean;
public static BeanMap create(Object bean) {
BeanMap.Generator gen = new BeanMap.Generator();
gen.setBean(bean);
return gen.create();
}
public abstract BeanMap newInstance(Object var1);
public abstract Class getPropertyType(String var1);
protected BeanMap() {
}
protected BeanMap(Object bean) {
this.setBean(bean);
}
public Object get(Object key) {
return this.get(this.bean, key);
}
public Object put(Object key, Object value) {
return this.put(this.bean, key, value);
}
public abstract Object get(Object var1, Object var2);
public abstract Object put(Object var1, Object var2, Object var3);
public void setBean(Object bean) {
this.bean = bean;
}
public Object getBean() {
return this.bean;
}
public void clear() {
throw new UnsupportedOperationException();
}
public boolean containsKey(Object key) {
return this.keySet().contains(key);
}
public boolean containsValue(Object value) {
Iterator it = this.keySet().iterator();
Object v;
do {
if (!it.hasNext()) {
return false;
}
v = this.get(it.next());
} while((value != null || v != null) && (value == null || !value.equals(v)));
return true;
}
public int size() {
return this.keySet().size();
}
public boolean isEmpty() {
return this.size() == 0;
}
public Object remove(Object key) {
throw new UnsupportedOperationException();
}
public void putAll(Map t) {
Iterator it = t.keySet().iterator();
while(it.hasNext()) {
Object key = it.next();
this.put(key, t.get(key));
}
}
public boolean equals(Object o) {
if (o != null && o instanceof Map) {
Map other = (Map)o;
if (this.size() != other.size()) {
return false;
} else {
Iterator it = this.keySet().iterator();
while(true) {
if (!it.hasNext()) {
return true;
}
Object key = it.next();
if (!other.containsKey(key)) {
return false;
}
Object v1 = this.get(key);
Object v2 = other.get(key);
if (v1 == null) {
if (v2 == null) {
continue;
}
break;
} else if (!v1.equals(v2)) {
break;
}
}
return false;
}
} else {
return false;
}
}
public int hashCode() {
int code = 0;
Object key;
Object value;
for(Iterator it = this.keySet().iterator(); it.hasNext(); code += (key == null ? 0 : key.hashCode()) ^ (value == null ? 0 : value.hashCode())) {
key = it.next();
value = this.get(key);
}
return code;
}
public Set entrySet() {
HashMap copy = new HashMap();
Iterator it = this.keySet().iterator();
while(it.hasNext()) {
Object key = it.next();
copy.put(key, this.get(key));
}
return Collections.unmodifiableMap(copy).entrySet();
}
public Collection values() {
Set keys = this.keySet();
List values = new ArrayList(keys.size());
Iterator it = keys.iterator();
while(it.hasNext()) {
values.add(this.get(it.next()));
}
return Collections.unmodifiableCollection(values);
}
public String toString() {
StringBuffer sb = new StringBuffer();
sb.append('{');
Iterator it = this.keySet().iterator();
while(it.hasNext()) {
Object key = it.next();
sb.append(key);
sb.append('=');
sb.append(this.get(key));
if (it.hasNext()) {
sb.append(", ");
}
}
sb.append('}');
return sb.toString();
}
public static class Generator extends AbstractClassGenerator {
private static final Source SOURCE = new Source(BeanMap.class.getName());
private static final BeanMap.Generator.BeanMapKey KEY_FACTORY;
private Object bean;
private Class beanClass;
private int require;
public Generator() {
super(SOURCE);
}
public void setBean(Object bean) {
this.bean = bean;
if (bean != null) {
this.beanClass = bean.getClass();
}
}
public void setBeanClass(Class beanClass) {
this.beanClass = beanClass;
}
public void setRequire(int require) {
this.require = require;
}
protected ClassLoader getDefaultClassLoader() {
return this.beanClass.getClassLoader();
}
protected ProtectionDomain getProtectionDomain() {
return ReflectUtils.getProtectionDomain(this.beanClass);
}
public BeanMap create() {
if (this.beanClass == null) {
throw new IllegalArgumentException("Class of bean unknown");
} else {
this.setNamePrefix(this.beanClass.getName());
return (BeanMap)super.create(KEY_FACTORY.newInstance(this.beanClass, this.require));
}
}
public void generateClass(ClassVisitor v) throws Exception {
new BeanMapEmitter(v, this.getClassName(), this.beanClass, this.require);
}
protected Object firstInstance(Class type) {
return ((BeanMap)ReflectUtils.newInstance(type)).newInstance(this.bean);
}
protected Object nextInstance(Object instance) {
return ((BeanMap)instance).newInstance(this.bean);
}
static {
KEY_FACTORY = (BeanMap.Generator.BeanMapKey)KeyFactory.create(BeanMap.Generator.BeanMapKey.class, KeyFactory.CLASS_BY_NAME);
}
interface BeanMapKey {
Object newInstance(Class var1, int var2);
}
}
}
方法二 :
map转对象: 解决类型转换问题
实体类:
实体类属性建议用包装类,不要用基本数据类型 !!!
package com.ihrm.domain.system;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import org.hibernate.annotations.DynamicInsert;
import org.hibernate.annotations.DynamicUpdate;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import java.io.Serializable;
@Entity
@Table(name = "pe_permission")
@Getter
@Setter
@ToString
@NoArgsConstructor
@DynamicInsert(true)
@DynamicUpdate(true)
public class Permission implements Serializable {
private static final long serialVersionUID = -4990810027542971546L;
/**
* 主键
*/
@Id
private String id;
/**
* 权限名称
*/
private String name;
/**
* 权限类型 1为菜单 2为功能 3为API
*/
private Integer type;
private String code;
/**
* 权限描述
*/
private String description;
private String pid;
private Integer enVisible;
public Permission(String name, Integer type, String code, String description) {
this.name = name;
this.type = type;
this.code = code;
this.description = description;
}
}
转换工具:
/**
* map 转 实体类
* @param map
* @return
* @throws Exception
*/
public Permission mapToBean(Map<String,Object> map)
throws Exception
{
Permission permission = new Permission();
if(map != null){
Field[] declaredFields = Permission.class.getDeclaredFields();
if(declaredFields != null){
for (Field declaredField : declaredFields)
{
declaredField.setAccessible(true);
Set<String> mapKeys = map.keySet();
for (String mapKey : mapKeys)
{
if(declaredField.getType().toString().contains("Integer"))//判断属性类型 进行转换,map中存放的是Object对象需要转换 实体类中有多少类型就加多少类型,实体类属性用包装类;
if(declaredField.getName().equals(mapKey)){
declaredField.set(permission,Integer.valueOf(map.get(mapKey).toString()));
break;
}
if(declaredField.getType().toString().contains("String") )//判断属性类型 进行转换;
if(declaredField.getName().equals(mapKey)){
declaredField.set(permission,map.get(mapKey));
break;
}
}
}
}
}
return permission;
}
service使用:
/**
* 1.保存权限
*/
public void save(Map<String,Object> map) throws Exception {
//设置主键的值
String id = idWorker.nextId()+"";
//1.通过map构造permission对象 扩展性比较好,但我运行时报类型转换错误
/* BeanMapUtils.mapToBean(map, Permission.class);
Permission perm = BeanMapUtils.mapToBean(map,Permission.class);*/
Permission perm = mapToBean(map);//新做的方法
perm.setId(id);
//2.根据类型构造不同的资源对象(菜单,按钮,api)
int type = perm.getType();
switch (type) {
case PermissionConstants.PERMISSION_MENU:
PermissionMenu menu = BeanMapUtils.mapToBean(map,PermissionMenu.class);
menu.setId(id);
permissionMenuDao.save(menu);
break;
case PermissionConstants.PERMISSION_POINT:
PermissionPoint point = BeanMapUtils.mapToBean(map,PermissionPoint.class);
point.setId(id);
permissionPointDao.save(point);
break;
case PermissionConstants.PERMISSION_API:
PermissionApi api = BeanMapUtils.mapToBean(map,PermissionApi.class);
api.setId(id);
permissionApiDao.save(api);
break;
default:
throw new CommonException(ResultCode.FAIL);
}
//3.保存
permissionDao.save(perm);
}
补充:
判断类型
Object param;
if (param instanceof Integer) {
} else if (param instanceof String) {
} else if (param instanceof Double) {
} else if (param instanceof Float) {
} else if (param instanceof Long) {
} else if (param instanceof Boolean) {
} else if (param instanceof Date) {
}
========================================================================================
六.以下是最优先最稳定最有效的map与模型互转类
6.1 map与模型互转工具类
BeanUtils
import java.beans.PropertyDescriptor;
import java.beans.PropertyEditor;
import java.beans.PropertyEditorSupport;
import java.sql.Time;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;
public class BeanUtils {
public static final String PROPERTY_NAME = "com.context.key.lowercase";
private static final boolean LOWERCASE = isLowercase();
private static ConcurrentHashMap<Class<?>, PropertyEditor> customEditors = new ConcurrentHashMap();
static ThreadLocal<Set> recurseBeanSet;
private static boolean isLowercase() {
String lowercase = System.getProperty("com..context.key.lowercase", "false");
return Boolean.valueOf(lowercase).booleanValue();
}
private BeanUtils() {
}
public static void registerCustomEditor(Class<?> clazz, PropertyEditor editor) {
customEditors.put(clazz, editor);
}
public static String getConvertedName(String name) {
return name != null && name.length() != 0 && !LOWERCASE ? Character.toUpperCase(name.charAt(0)) + name.substring(1) : name;
}
public static <T> T map2Bean(Map map, T obj) {
BeanWrapper bw = new BeanWrapperImpl(obj);
PropertyDescriptor[] props = bw.getPropertyDescriptors();
PropertyDescriptor[] var4 = props;
int var5 = props.length;
for(int var6 = 0; var6 < var5; ++var6) {
PropertyDescriptor pd = var4[var6];
String name = pd.getName();
if (bw.isWritableProperty(name) && bw.isReadableProperty(name)) {
Class class0 = pd.getPropertyType();
String convertedName;
Object value;
if (Enum.class.isAssignableFrom(class0)) {
convertedName = getConvertedName(name);
value = map.get(convertedName);
if (value != null) {
if (value.getClass() == class0) {
bw.setPropertyValue(name, value);
} else {
String enumValue = String.valueOf(value);
if (enumValue.length() > 0) {
Enum v = Enum.valueOf(class0, enumValue);
bw.setPropertyValue(name, v);
}
}
}
} else {
convertedName = getConvertedName(name);
value = map.get(convertedName);
if (value != null) {
bw.setPropertyValue(name, value);
}
}
}
}
return bw.getWrappedInstance();
}
public static <T> T map2Bean(Map map, Class<T> clazz) {
BeanWrapper bw = new BeanWrapperImpl(clazz);
Iterator var3 = customEditors.entrySet().iterator();
while(var3.hasNext()) {
Entry<Class<?>, PropertyEditor> en = (Entry)var3.next();
bw.registerCustomEditor((Class)en.getKey(), (PropertyEditor)en.getValue());
}
PropertyDescriptor[] props = bw.getPropertyDescriptors();
PropertyDescriptor[] var15 = props;
int var5 = props.length;
for(int var6 = 0; var6 < var5; ++var6) {
PropertyDescriptor pd = var15[var6];
String name = pd.getName();
if (bw.isWritableProperty(name) && bw.isReadableProperty(name)) {
Class class0 = pd.getPropertyType();
String convertedName;
Object value;
if (Enum.class.isAssignableFrom(class0)) {
convertedName = getConvertedName(name);
value = map.get(convertedName);
if (value != null) {
if (value.getClass() == class0) {
bw.setPropertyValue(name, value);
} else {
String enumValue = String.valueOf(value);
if (enumValue.length() > 0) {
Enum v = Enum.valueOf(class0, String.valueOf(value));
bw.setPropertyValue(name, v);
}
}
}
} else {
convertedName = getConvertedName(name);
value = map.get(convertedName);
if (value != null) {
bw.setPropertyValue(name, value);
}
}
}
}
return bw.getWrappedInstance();
}
public static Map bean2Map(Object beanObject) {
BeanWrapperImpl bean = new BeanWrapperImpl(beanObject);
PropertyDescriptor[] desc = bean.getPropertyDescriptors();
HashMap dataMap = new HashMap(desc.length);
try {
for(int i = 0; i < desc.length; ++i) {
String name = desc[i].getName();
if (bean.isWritableProperty(name) && bean.isReadableProperty(name)) {
Object object = bean.getPropertyValue(name);
if (object != null) {
String convertedName = getConvertedName(name);
dataMap.put(convertedName, object);
}
}
}
return dataMap;
} catch (Exception var8) {
throw new PeRuntimeException("pe.core.util.bean2map_fail", var8);
}
}
public static List<Map> listBean2ListMap(List list) {
List<Map> result = new ArrayList();
Iterator it = list.iterator();
while(it.hasNext()) {
Map tmp = bean2Map(it.next());
result.add(tmp);
}
return result;
}
public static <T> List<T> listMap2ListBean(List list, Class<T> class0) {
List<T> result = new ArrayList();
Iterator it = list.iterator();
while(it.hasNext()) {
T t = map2Bean((Map)it.next(), class0);
result.add(t);
}
return result;
}
public static Map bean2MapRecurse(Object beanObject) {
Set set = (Set)recurseBeanSet.get();
if (set.contains(beanObject)) {
return null;
} else {
set.add(beanObject);
try {
BeanWrapperImpl bean = new BeanWrapperImpl(beanObject);
PropertyDescriptor[] desc = bean.getPropertyDescriptors();
HashMap dataMap = new HashMap(desc.length);
try {
for(int i = 0; i < desc.length; ++i) {
String name = desc[i].getName();
if (bean.isWritableProperty(name) && bean.isReadableProperty(name)) {
Object object = bean.getPropertyValue(name);
if (object != null) {
String convertedName = getConvertedName(name);
Class class0 = object.getClass();
if (!class0.getName().startsWith("java") && !Enum.class.isAssignableFrom(class0)) {
Map subMap = bean2MapRecurse(object);
if (subMap != null) {
Iterator it = subMap.entrySet().iterator();
while(it.hasNext()) {
Entry entry = (Entry)it.next();
dataMap.put(convertedName + "_" + entry.getKey(), entry.getValue());
}
}
} else {
dataMap.put(convertedName, object);
}
}
}
}
HashMap var18 = dataMap;
return var18;
} catch (Exception var16) {
throw new PeRuntimeException("pe.core.util.bean2map_fail", var16);
}
} finally {
set.remove(beanObject);
}
}
}
public static void list2Bean(List<?> srcBeanObject, Object destBeanObject, String listPropName) {
BeanWrapperImpl destBean = new BeanWrapperImpl(destBeanObject);
destBean.setPropertyValue(listPropName, srcBeanObject);
}
public static <T> T bean2Bean(Object srcBeanObject, Class<T> class0) {
try {
T t = class0.newInstance();
if (srcBeanObject instanceof List) {
list2Bean((List)srcBeanObject, t, "list");
} else {
bean2Bean(srcBeanObject, t);
}
return t;
} catch (Exception var3) {
throw new PeRuntimeException("pe.core.util.bean2bean_fail", var3);
}
}
public static void bean2Bean(Object srcBeanObject, Object destBeanObject) {
BeanWrapperImpl srcBean = new BeanWrapperImpl(srcBeanObject);
BeanWrapperImpl destBean = new BeanWrapperImpl(destBeanObject);
PropertyDescriptor[] destDesc = destBean.getPropertyDescriptors();
try {
for(int i = 0; i < destDesc.length; ++i) {
String name = destDesc[i].getName();
if (destBean.isWritableProperty(name) && srcBean.isReadableProperty(name)) {
Object srcValue = srcBean.getPropertyValue(name);
if (srcValue != null) {
destBean.setPropertyValue(name, srcValue);
}
}
}
} catch (Exception var8) {
throw new PeRuntimeException("pe.core.util.bean2bean_fail", var8);
}
}
public static <T> T map2BeanStrict(Map map, T obj) {
BeanWrapper bw = new BeanWrapperImpl(obj);
PropertyDescriptor[] props = bw.getPropertyDescriptors();
PropertyDescriptor[] var4 = props;
int var5 = props.length;
for(int var6 = 0; var6 < var5; ++var6) {
PropertyDescriptor pd = var4[var6];
String name = pd.getName();
if (bw.isWritableProperty(name) && bw.isReadableProperty(name)) {
Class class0 = pd.getPropertyType();
Object value;
if (Enum.class.isAssignableFrom(class0)) {
value = map.get(name);
if (value != null) {
if (value.getClass() == class0) {
bw.setPropertyValue(name, value);
} else {
Enum v = Enum.valueOf(class0, String.valueOf(value));
bw.setPropertyValue(name, v);
}
}
} else {
value = map.get(name);
if (value != null) {
bw.setPropertyValue(name, value);
}
}
}
}
return bw.getWrappedInstance();
}
public static <T> T map2BeanStrict(Map map, Class<T> clazz) {
BeanWrapper bw = new BeanWrapperImpl(clazz);
PropertyDescriptor[] props = bw.getPropertyDescriptors();
PropertyDescriptor[] var4 = props;
int var5 = props.length;
for(int var6 = 0; var6 < var5; ++var6) {
PropertyDescriptor pd = var4[var6];
String name = pd.getName();
if (bw.isWritableProperty(name) && bw.isReadableProperty(name)) {
Class class0 = pd.getPropertyType();
Object value;
if (Enum.class.isAssignableFrom(class0)) {
value = map.get(name);
if (value != null) {
if (value.getClass() == class0) {
bw.setPropertyValue(name, value);
} else {
Enum v = Enum.valueOf(class0, String.valueOf(value));
bw.setPropertyValue(name, v);
}
}
} else {
value = map.get(name);
if (value != null) {
bw.setPropertyValue(name, value);
}
}
}
}
return bw.getWrappedInstance();
}
static {
registerCustomEditor(Date.class, new BeanUtils.CustomPropertyEditor() {
public Object getValue() {
return DateUtils.toDate(this.value);
}
});
registerCustomEditor(java.sql.Date.class, new BeanUtils.CustomPropertyEditor() {
public Object getValue() {
return DateUtils.toSqlDate(this.value);
}
});
registerCustomEditor(Time.class, new BeanUtils.CustomPropertyEditor() {
public Object getValue() {
return DateUtils.toTime(this.value);
}
});
registerCustomEditor(Timestamp.class, new BeanUtils.CustomPropertyEditor() {
public Object getValue() {
return DateUtils.toTimestamp(this.value);
}
});
recurseBeanSet = new ThreadLocal<Set>() {
protected synchronized Set initialValue() {
return new HashSet();
}
};
}
private static class CustomPropertyEditor extends PropertyEditorSupport {
protected Object value;
private CustomPropertyEditor() {
}
public void setAsText(String text) throws IllegalArgumentException {
this.value = text;
}
public void setValue(Object value) {
this.value = value;
}
}
}
使用
6.2 模型转map
User user = new user("小明",18)
Map map = BeanUtils.bean2Map(user)
6.3 map转模型
Map resultMap = new HashMap();
resultMap .put("Username","小明");
resultMap .put("Age","18");
User user = BeanUusertils.map2Bean(resultMap, User.class);
感谢赞助与支持!
原文作者:再遇当年
原文地址: https://blog.csdn.net/qq_15204179/article/details/86677123
本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
原文地址: https://blog.csdn.net/qq_15204179/article/details/86677123
本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
相关文章