文章目录
【Java对象转换】002- Java 对象与 Map 互转
一、Java 对象与 Map 概述
1、Java 对象
- Java对象是数据和处理可用数据的过程的组合;
- 对象既有状态又有行为 。 在Java中,使用关键字“ new”创建对象;
- 对象是从称为类的模板创建的;
- 对象是类的实例。
2、Map
参考本人文章:Java中Map使用详解 https://blog.csdn.net/qq_29689343/article/details/109853787
二、Java 对象与 Map 互转
下面的工具类在具体使用的时候需要做具体调整,比如捕捉异常!
1、使用 commons.beanutils 转换
第一步:在 pom.xml 下引入依赖
<dependency>
<groupId>commons-beanutils</groupId>
<artifactId>commons-beanutils</artifactId>
<version>1.9.4</version>
</dependency>
第二步:写个工具类
package com.zibo.study.object_switch.beanutils;
import org.apache.commons.beanutils.BeanMap;
import org.apache.commons.beanutils.BeanUtils;
import java.util.Map;
public class ObjectAndMapUtil {
private ObjectAndMapUtil() { }
// map 转 java 对象
public static <T> T mapToObject(Map<String, Object> map, Class<T> clazz)
throws Exception {
if (map == null) {
return null;
}
T t = clazz.newInstance();
BeanUtils.populate(t, map);
return t;
}
// java 对象转 map
public static Map<?, ?> objectToMap(Object obj) {
if (obj == null) return null;
return new BeanMap(obj);
}
}
第三步:代码演示
package com.zibo.study.object_switch.beanutils;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
public class Main {
public static void main(String[] args) {
// 1、创建 Java 对象
Dog dog = new Dog("瓦豆", 2, 20.5, Arrays.asList("吃骨头", "玩球"));
// 2、使用工具类转 map
System.out.println("2、使用工具类转 map");
Map<?, ?> dogMap = ObjectAndMapUtil.objectToMap(dog);
System.out.println(dogMap.get("name"));
System.out.println(dogMap.get("age"));
System.out.println(dogMap.get("weight"));
System.out.println(dogMap.get("hobbies"));
// 3、使用工具类转 object
System.out.println("3、使用工具类转 object");
try {
Map<String, Object> map = new HashMap<>();
map.put("name", "瓦豆");
map.put("age", 2);
map.put("weight", 20.5);
map.put("hobbies", Arrays.asList("吃骨头", "玩球"));
Dog mapToDog = ObjectAndMapUtil.mapToObject(map, Dog.class);
// Dog mapToDog = ObjectAndMapUtil.mapToObject((Map<String, Object>) dogMap, Dog.class);
System.out.println(mapToDog);
} catch (Exception e) {
e.printStackTrace();
}
}
}
第四步:运行结果
2、使用工具类转 map
瓦豆
2
20.5
[吃骨头, 玩球]
3、使用工具类转 object
(中间忽略了一些日志)
Dog(name=瓦豆, age=2, weight=20.5, hobbies=[吃骨头, 玩球])
2、使用Introspector转换
第一步:写个工具类
package com.zibo.study.object_switch.beanutils;
import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
public class ObjectAndMapUtil2 {
// map 转 java 对象
public static <T> T mapToObject(Map<String, Object> map, Class<T> clazz) throws IntrospectionException, InstantiationException, IllegalAccessException, InvocationTargetException {
if (map == null) return null;
T t = clazz.newInstance();
BeanInfo beanInfo = Introspector.getBeanInfo(t.getClass());
PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
for (PropertyDescriptor property : propertyDescriptors) {
Method setter = property.getWriteMethod();
if (setter != null) setter.invoke(t, map.get(property.getName()));
}
return t;
}
// java 对象转 map
public static Map<String, Object> objectToMap(Object obj) throws IntrospectionException, InvocationTargetException, IllegalAccessException {
if (obj == null) return null;
Map<String, Object> map = new HashMap<>();
BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
PropertyDescriptor[] propertyDescriptors = beanInfo
.getPropertyDescriptors();
for (PropertyDescriptor property : propertyDescriptors) {
String key = property.getName();
if (key.compareToIgnoreCase("class") == 0) continue;
Method getter = property.getReadMethod();
Object value = getter != null ? getter.invoke(obj) : null;
map.put(key, value);
}
return map;
}
}
第二步:代码演示
package com.zibo.study.object_switch.beanutils;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
public class Main {
public static void main(String[] args) throws Exception {
// 1、创建 Java 对象
Dog dog = new Dog("瓦豆", 2, 20.5, Arrays.asList("吃骨头", "玩球"));
// 2、使用工具类转 map
System.out.println("2、使用工具类转 map");
Map<?, ?> dogMap = ObjectAndMapUtil2.objectToMap(dog);
System.out.println(dogMap.get("name"));
System.out.println(dogMap.get("age"));
System.out.println(dogMap.get("weight"));
System.out.println(dogMap.get("hobbies"));
// 3、使用工具类转 object
System.out.println("3、使用工具类转 object");
try {
Map<String, Object> map = new HashMap<>();
map.put("name", "瓦豆");
map.put("age", 2);
map.put("weight", 20.5);
map.put("hobbies", Arrays.asList("吃骨头", "玩球"));
Dog mapToDog = ObjectAndMapUtil2.mapToObject(map, Dog.class);
// Dog mapToDog = ObjectAndMapUtil.mapToObject((Map<String, Object>) dogMap, Dog.class);
System.out.println(mapToDog);
} catch (Exception e) {
e.printStackTrace();
}
}
}
第三步:运行结果
2、使用工具类转 map
瓦豆
2
20.5
[吃骨头, 玩球]
3、使用工具类转 object
Dog(name=瓦豆, age=2, weight=20.5, hobbies=[吃骨头, 玩球])
3、使用reflect转换
第一步:写个工具类
package com.zibo.study.object_switch.beanutils;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.HashMap;
import java.util.Map;
public class ObjectAndMapUtil3 {
// map 转 java 对象
public static <T> T mapToObject(Map<String, Object> map, Class<T> clazz) throws InstantiationException, IllegalAccessException {
if (map == null) return null;
T t = clazz.newInstance();
Field[] fields = clazz.getDeclaredFields();
for (Field field : fields) {
int mod = field.getModifiers();
if (Modifier.isFinal(mod) || Modifier.isStatic(mod)) continue;
field.setAccessible(true);
field.set(t, map.get(field.getName()));
}
return t;
}
// java 对象转 map
public static Map<String, Object> objectToMap(Object obj) throws IllegalAccessException {
if (obj == null) return null;
Map<String, Object> map = new HashMap<>();
Field[] declaredFields = obj.getClass().getDeclaredFields();
for (Field field : declaredFields) {
field.setAccessible(true);
map.put(field.getName(), field.get(obj));
}
return map;
}
}
第二步:代码演示
package com.zibo.study.object_switch.beanutils;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
public class Main {
public static void main(String[] args) throws Exception {
// 1、创建 Java 对象
Dog dog = new Dog("瓦豆", 2, 20.5, Arrays.asList("吃骨头", "玩球"));
// 2、使用工具类转 map
System.out.println("2、使用工具类转 map");
Map<?, ?> dogMap = ObjectAndMapUtil3.objectToMap(dog);
System.out.println(dogMap.get("name"));
System.out.println(dogMap.get("age"));
System.out.println(dogMap.get("weight"));
System.out.println(dogMap.get("hobbies"));
// 3、使用工具类转 object
System.out.println("3、使用工具类转 object");
try {
Map<String, Object> map = new HashMap<>();
map.put("name", "瓦豆");
map.put("age", 2);
map.put("weight", 20.5);
map.put("hobbies", Arrays.asList("吃骨头", "玩球"));
Dog mapToDog = ObjectAndMapUtil3.mapToObject(map, Dog.class);
// Dog mapToDog = ObjectAndMapUtil.mapToObject((Map<String, Object>) dogMap, Dog.class);
System.out.println(mapToDog);
} catch (Exception e) {
e.printStackTrace();
}
}
}
第三步:运行结果
2、使用工具类转 map
瓦豆
2
20.5
[吃骨头, 玩球]
3、使用工具类转 object
Dog(name=瓦豆, age=2, weight=20.5, hobbies=[吃骨头, 玩球])
4、使用 net.sf.cglib.beans.BeanMap 转换
第一步:在 pom.xml 下引入依赖
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib</artifactId>
<version>3.3.0</version>
</dependency>
第二步:写个工具类
package com.zibo.study.object_switch.beanutils;
import com.google.common.collect.Maps;
import net.sf.cglib.beans.BeanMap;
import java.util.Map;
public class ObjectAndMapUtil4 {
// map 转 java 对象
public static <T> T mapToObject(Map<String, Object> map, Class<T> clazz) throws InstantiationException, IllegalAccessException {
T t = clazz.newInstance();
BeanMap beanMap = BeanMap.create(t);
beanMap.putAll(map);
return t;
}
// java 对象转 map
public static Map<String, Object> objectToMap(Object obj) {
if (obj == null) return null;
Map<String, Object> map = Maps.newHashMap();
BeanMap beanMap = BeanMap.create(obj);
for (Object key : beanMap.keySet()) {
map.put(key + "", beanMap.get(key));
}
return map;
}
}
第三步:代码演示
package com.zibo.study.object_switch.beanutils;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
public class Main {
public static void main(String[] args) {
// 1、创建 Java 对象
Dog dog = new Dog("瓦豆", 2, 20.5, Arrays.asList("吃骨头", "玩球"));
// 2、使用工具类转 map
System.out.println("2、使用工具类转 map");
Map<?, ?> dogMap = ObjectAndMapUtil4.objectToMap(dog);
System.out.println(dogMap.get("name"));
System.out.println(dogMap.get("age"));
System.out.println(dogMap.get("weight"));
System.out.println(dogMap.get("hobbies"));
// 3、使用工具类转 object
System.out.println("3、使用工具类转 object");
try {
Map<String, Object> map = new HashMap<>();
map.put("name", "瓦豆");
map.put("age", 2);
map.put("weight", 20.5);
map.put("hobbies", Arrays.asList("吃骨头", "玩球"));
Dog mapToDog = ObjectAndMapUtil4.mapToObject(map, Dog.class);
// Dog mapToDog = ObjectAndMapUtil.mapToObject((Map<String, Object>) dogMap, Dog.class);
System.out.println(mapToDog);
} catch (Exception e) {
e.printStackTrace();
}
}
}
第四步:运行结果
2、使用工具类转 map
瓦豆
2
20.5
[吃骨头, 玩球]
3、使用工具类转 object
Dog(name=瓦豆, age=2, weight=20.5, hobbies=[吃骨头, 玩球])
5、使用 json 转换
第一步:在 pom.xml 下引入依赖
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.80</version>
</dependency>
第二步:写一个工具类
package com.zibo.study.object_switch.beanutils;
import com.alibaba.fastjson.JSONObject;
import java.util.Map;
public class ObjectAndMapUtil5 {
// map 转 java 对象
public static <T> T mapToObject(Map<String, Object> map, Class<T> clazz) {
String jsonStr = JSONObject.toJSONString(map);
return JSONObject.parseObject(jsonStr, clazz);
}
// java 对象转 map
public static Map<String, Object> objectToMap(Object obj) {
if(obj == null) return null;
String jsonStr = JSONObject.toJSONString(obj);
return JSONObject.parseObject(jsonStr);
}
}
第三步:代码演示
package com.zibo.study.object_switch.beanutils;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
public class Main {
public static void main(String[] args) {
// 1、创建 Java 对象
Dog dog = new Dog("瓦豆", 2, 20.5, Arrays.asList("吃骨头", "玩球"));
// 2、使用工具类转 map
System.out.println("2、使用工具类转 map");
Map<?, ?> dogMap = ObjectAndMapUtil5.objectToMap(dog);
System.out.println(dogMap.get("name"));
System.out.println(dogMap.get("age"));
System.out.println(dogMap.get("weight"));
System.out.println(dogMap.get("hobbies"));
// 3、使用工具类转 object
System.out.println("3、使用工具类转 object");
try {
Map<String, Object> map = new HashMap<>();
map.put("name", "瓦豆");
map.put("age", 2);
map.put("weight", 20.5);
map.put("hobbies", Arrays.asList("吃骨头", "玩球"));
Dog mapToDog = ObjectAndMapUtil5.mapToObject(map, Dog.class);
// Dog mapToDog = ObjectAndMapUtil.mapToObject((Map<String, Object>) dogMap, Dog.class);
System.out.println(mapToDog);
} catch (Exception e) {
e.printStackTrace();
}
}
}
第四步:运行结果
2、使用工具类转 map
瓦豆
2
20.5
["吃骨头","玩球"]
3、使用工具类转 object
Dog(name=瓦豆, age=2, weight=20.5, hobbies=[吃骨头, 玩球])
三、 后记
暂仅记录这么多,后续若有更好的方法会进行补充!
参考文章:https://blog.csdn.net/liuyunyihao/article/details/86597002