反射方式实现
import com.wc.domain.User;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* @author JngKang
* @date 2022-04-18 12:16
* @description Map与JavaBean相互转换工具类
*/
public class MapBeanUtil {
/**
* @param obj 待转化的实体对象
* @return java.util.Map<java.lang.String,java.lang.Object>
* @description 将实体对象转化为HashMap
*/
public static Map<String, Object> bean2Map(Object obj) {
Map<String, Object> map = new LinkedHashMap<>();
Class<?> clazz = obj.getClass();
for (Field field : clazz.getDeclaredFields()) {
field.setAccessible(true);
String fieldName = field.getName();
Object value = null;
try {
value = field.get(obj);
} catch (IllegalAccessException e) {
e.printStackTrace();
}
if (value == null){
value = "";
}
map.put(fieldName, value);
}
return map;
}
/**
* @param map 待转化数组
* @param clazz 转化的实体
* @return T 返回相应的实体
* @description 使用反射中内省的方式将map中的数据转化为相应的实体
*/
public static <T> T map2Bean(Map<String, Object> map, Class<T> clazz) {
if (map == null) {
return null;
}
T res = null;
try {
res = clazz.getDeclaredConstructor().newInstance();
//获取到所有属性,不包括继承的属性
Field[] fields = clazz.getDeclaredFields();
for (Field field : fields) {
//获取字段的修饰符
int mod = field.getModifiers();
if (Modifier.isStatic(mod) || Modifier.isFinal(mod)) {
continue;
}
//设置对象的访问权限
field.setAccessible(true);
//根据属性名称去map获取value
if(map.containsKey(field.getName())) {
//给对象赋值
field.set(res, map.get(field.getName()));
}
}
} catch (Exception e) {
e.printStackTrace();
}
return res;
}
public static void main(String[] args) throws Exception {
Map<String, Object> map = new HashMap<>();
map.put("id", 10000L);
map.put("name", "wwk");
map.put("gender", true);
map.put("email", "asf");
map.put("tel", "123");
map.put("credits", 100);
map.put("status", 3);
User user = map2Bean(map, User.class);
System.out.println(user);
Map<String, Object> res = bean2Map(user);
res.forEach((k, v) -> System.out.println(k + " - " + v));
}
}
内省方式实现
import com.wc.domain.User;
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;
/**
* @author JngKang
* @date 2022-04-18 09:19
* @description Map与JavaBean相互转换工具类
*/
public class BeanMapTransUtil {
/**
* @param map 待转化数组
* @param clazz 转化的实体
* @return T 返回相应的实体
* @description 使用反射中内省的方式将map中的数据转化为相应的实体
*/
public static <T> T map2Bean(Map<String, Object> map, Class<T> clazz) throws NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException, IntrospectionException {
T obj = clazz.getDeclaredConstructor().newInstance();
// 根据clazz获取BeanInfo
BeanInfo beanInfo = Introspector.getBeanInfo(clazz, Object.class);
// 获取所有成员变量名
PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors();
// 遍历
for (PropertyDescriptor pd : pds) {
// 获取Setter方法
Method writeMethod = pd.getWriteMethod();
// 获取成员变量名,并为其赋值
writeMethod.invoke(obj, map.get(pd.getName()));
}
return obj;
}
/**
* @param obj 待转化的实体对象
* @return java.util.Map<java.lang.String,java.lang.Object>
* @description 将实体对象转化为HashMap
*/
public static Map<String, Object> bean2Map(Object obj) throws IntrospectionException, InvocationTargetException, IllegalAccessException {
Map<String, Object> map = new HashMap<>();
// 获取实体对象的字节码文件
Class<?> clazz = obj.getClass();
// 获取BeanInfo
BeanInfo beanInfo = Introspector.getBeanInfo(clazz, Object.class);
// 获取所有的成员变量名
PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors();
// 遍历
for (PropertyDescriptor pd : pds) {
// 获取成员变量名
String field = pd.getName();
// 获取Getter方法
Method readMethod = pd.getReadMethod();
// 获取成员变量的值
Object value = readMethod.invoke(obj);
// 存入map
map.put(field, value);
}
return map;
}
public static void main(String[] args) throws IntrospectionException, InvocationTargetException, NoSuchMethodException, InstantiationException, IllegalAccessException {
Map<String, Object> map = new HashMap<>();
map.put("id", 10000L);
map.put("name", "wwk");
map.put("gender", true);
map.put("email", "asf");
map.put("tel", "123");
map.put("credits", 100);
map.put("status", 3);
User user = map2Bean(map, User.class);
System.out.println(user);
Map<String, Object> res = bean2Map(user);
res.forEach((k, v) -> System.out.println(k + " - " + v));
}
}
测试中使用的实体:
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
/**
* @author JngKang
* @date 2022-04-02 15:47
* @description
*/
@Setter
@Getter
@NoArgsConstructor
@AllArgsConstructor
@Builder
@ToString
public class User {
private Long id;
private String name;
private Boolean gender;
private String email;
private String tel;
private Integer credits;
private Integer status;
}