package com.generic.type;
import java.io.Serializable;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.HashMap;
import java.util.Map;
public class Generic05 {
static class User implements Serializable {
private static final long serialVersionUID = -6148496197242680896L;
public User() {
}
public User(Long id, String name) {
this.id = id;
this.name = name;
}
private Long id;
private String name;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + ''' +
'}';
}
}
public static void main(String[] args) throws Exception {
User user = new User(1L, "zs");
Map map = obj2Map(user);
System.out.println(map);
User user1 = map2Obj(map, User.class);
System.out.println(user1);
}
/**
* 对象转map
*
* @param obj
* @param <T>
* @return
* @throws IllegalAccessException
*/
public static <T> Map obj2Map(T obj) throws IllegalAccessException {
Map map = new HashMap<>();
// 获取所有字段:通过 getClass() 方法获取 Class 对象,然后获取这个类所有字段
Field[] fields = obj.getClass().getDeclaredFields();
for (Field field : fields) {
// 开放字段操作权限
field.setAccessible(true);
// 设置值
map.put(field.getName(), field.get(obj));
}
return map;
}
/**
* map转对象
*
* @param map
* @param cla
* @param <T>
* @return
* @throws Exception
*/
public static <T> T map2Obj(Map<Object, Object> map, Class<T> cla) throws Exception {
if (map == null) {
return null;
}
if (cla == null) {
return null;
}
T obj = cla.getConstructor().newInstance();
Field[] fields = cla.getDeclaredFields();
for (Field field : fields) {
int mod = field.getModifiers();
if (Modifier.isStatic(mod) || Modifier.isFinal(mod)) {
continue;
}
field.setAccessible(true);
if (map.containsKey(field.getName())) {
field.set(obj, map.get(field.getName()));
}
}
return obj;
}
}