package com.application.util;
import com.alibaba.fastjson.JSON;
import org.springframework.util.ObjectUtils;
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.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class JavaBeanUtils {
/**
* 实体类 转 Map
* @param bean 要转化的JavaBean 对象
* @param flagNull true 去除Bean字段空值, false Bean空字段,同样生成Map
* @return 转化出来的 Map 对象
* @throws IntrospectionException 如果分析类属性失败
* @throws IllegalAccessError 如果实例化 JavaBean 失败
* @throws InvocationTargetException 如果调用属性的 setter 方法失败
*/
public static Map<String, Object> convertBeanToMap(Object bean, boolean flagNull) throws IntrospectionException, IllegalAccessException, InvocationTargetException {
Class type = bean.getClass();
Map<String, Object> returnMap = new HashMap<>();
BeanInfo beanInfo = Introspector.getBeanInfo(type);
PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
for (int i = 0; i < propertyDescriptors.length; i++) {
PropertyDescriptor descriptor = propertyDescriptors[i];
String propertyName = descriptor.getName();
if (!"class".equals(propertyName)) {
Method readMethod = descriptor.getReadMethod();
Object result = readMethod.invoke(bean, new Object[0]);
if (flagNull) {
if (!ObjectUtils.isEmpty(result)) {
returnMap.put(propertyName, result);
}
} else {
if (ObjectUtils.isEmpty(result)) {
returnMap.put(propertyName, "");
} else {
returnMap.put(propertyName, result);
}
}
}
}
return returnMap;
}
/**
* 实体类 转 Map
* @param obj
* @return
*/
public static Map<String, Object> beanToMap(Object obj) {
Map<String, Object> params = JSON.parseObject(JSON.toJSONString(obj), Map.class);
return params;
}
/**
* Map转实体类
*
* @return
*/
public static <T> T mapToBean(Map<String, Object> params, Class<T> clazz) {
T obj = JSON.parseObject(JSON.toJSONString(params), clazz);
return obj;
}
/**
* list<Bean>转List<Map>
* @return
*/
public static <T> List<Map<String,Object>>beanListToMapList(List<T> beanList) {
List<Map<String,Object>> resultList = new ArrayList<Map<String,Object>>();
for (T bean : beanList) {
Map<String,Object> map = beanToMap(bean);
resultList.add(map);
}
return resultList;
}
}