java Object和Map之间的转换(附完整源码)
import java.util.HashMap;
import java.util.Map;
public class ObjectMapConversion {
public static void main(String[] args) {
// 创建一个对象
Person person = new Person("Tom", 20);
// 将对象转换为 Map
Map<String, Object> personMap = objectToMap(person);
System.out.println("对象转换为 Map:" + personMap);
// 将 Map 转换为对象
Person newPerson = mapToObject(personMap, Person.class);
System.out.println("Map 转换为对象:" + newPerson);
}
/**
* 将对象转换为 Map
* @param obj 对象
* @return 对象对应的 Map
*/
public static Map<String,Object> objectToMap(Object obj) {
Map<String, Object> map = new HashMap<>();
for (java.lang.reflect.Field field : obj.getClass().getDeclaredFields()) {
try {
field.setAccessible(true);
map.put(field.getName(), field.get(obj));
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
return map;
}
/**
* 将 Map 转换为指定类型的对象
* @param map Map
* @param clazz 对象类型
* @param <T> 对象类型
* @return 对象
*/
public static <T> T mapToObject(Map<String,Object> map, Class<T> clazz) {
T obj = null;
try {
obj = clazz.newInstance();
for (java.lang.reflect.Field field : obj.getClass().getDeclaredFields()) {
field.setAccessible(true);
Object value = map.get(field.getName());
if (value != null) {
field.set(obj, value);
}
}
} catch (InstantiationException | IllegalAccessException e) {
e.printStackTrace();
}
return obj;
}
/**
* 人员类
*/
static class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
}