我这里测试的实体类字段内容如下:
/**
* @author xxx
* @Description
*/
@Getter
@Setter
public class TestClass implements Serializable {
/** 内容1 */
private String stockDays;
/** 内容2 */
private int pageSize = 0;
/** 内容3 */
private int pageNum = 0;
/** 内容4 */
private String actCount;
}
公共类:
package xxx.xxxx.xxxxx.xxxxxx;
import com.alibaba.fastjson.JSON;
import org.apache.poi.ss.formula.functions.T;
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.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.Date;
import java.util.HashMap;
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;
}
/**
* 实体类转map
* @param obj
* @return
*/
public static Map<String, Object> convertBeanToMap(Object obj) {
if (obj == null) {
return null;
}
Map<String, Object> map = new HashMap<String, Object>();
try {
BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
for (PropertyDescriptor property : propertyDescriptors) {
String key = property.getName();
// 过滤class属性
if (!key.equals("class")) {
// 得到property对应的getter方法
Method getter = property.getReadMethod();
Object value = getter.invoke(obj);
if(null==value){
map.put(key,"");
}else{
map.put(key,value);
}
}
}
} catch (Exception e) {
System.out.println("convertBean2Map Error :" + e);
}
return map;
}
/**
* map 转实体类
* @param clazz
* @param map
* @param
* @return
*/
public static T convertMapToBean(Class clazz, Map<String,Object> map) {
T obj = null;
try {
BeanInfo beanInfo = Introspector.getBeanInfo(clazz);
obj = (T) clazz.newInstance(); // 创建 JavaBean 对象
// 给 JavaBean 对象的属性赋值
PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
for (int i = 0; i < propertyDescriptors.length; i++) {
PropertyDescriptor descriptor = propertyDescriptors[i];
String propertyName = descriptor.getName();
if (map.containsKey(propertyName)) {
// 下面一句可以 try 起来,这样当一个属性赋值失败的时候就不会影响其他属性赋值。
Object value = map.get(propertyName);
if ("".equals(value)) {
value = null;
}
Object[] args = new Object[1];
args[0] = value;
descriptor.getWriteMethod().invoke(obj, args);
}
}
} catch (IllegalAccessException e) {
System.out.println("convertMapToBean 实例化JavaBean失败 Error:" + e);
} catch (IntrospectionException e) {
System.out.println("convertMapToBean 分析类属性失败 Error:" + e);
} catch (IllegalArgumentException e) {
System.out.println("convertMapToBean 映射错误 Error:" + e);
} catch (InstantiationException e) {
System.out.println("convertMapToBean 实例化 JavaBean 失败 Error:" + e);
}catch (InvocationTargetException e){
System.out.println("convertMapToBean字段映射失败 Error:" + e);
}catch (Exception e){
System.out.println("convertMapToBean Error:" + e);
}
return (T) obj;
}
/**
* 将map通过反射转化为实体
* @param map
* @param o
* @return
* @throws Exception
*/
public static Object MapToModel(Map<String,Object> map,Object o) throws Exception{
if (!map.isEmpty()) {
for (String k : map.keySet()) {
Object v =null;
if (!k.isEmpty()) {
v = map.get(k);
}
Field[] fields = null;
fields = o.getClass().getDeclaredFields();
String clzName = o.getClass().getSimpleName();
for (Field field : fields) {
int mod = field.getModifiers();
if (field.getName().toUpperCase().equals(k.toUpperCase())) {
field.setAccessible(true);
//region–进行类型判断
String type=field.getType().toString();
if (type.endsWith("String")){
if (v!=null){
v=v.toString();
}else {
v="";
}
}
if (type.endsWith("Date")){
v=new Date(v.toString());
}
if (type.endsWith("Boolean")){
v=Boolean.getBoolean(v.toString());
}
if (type.endsWith("int")){
v=new Integer(v.toString());
}
if (type.endsWith("Long")){
v=new Long(v.toString());
}
//endregion
field.set(o, v);
}
}
}
}
return o;
}
/**
* 实体对象转成Map
* @param obj 实体对象
* @return
*/
public static Map<String, Object> objectToMap(Object obj) {
Map<String, Object> map = new HashMap<>();
if (obj == null) {
return map;
}
Class clazz = obj.getClass();
Field[] fields = clazz.getDeclaredFields();
try {
for (Field field : fields) {
field.setAccessible(true);
Object objValue = field.get(obj);
map.put(field.getName(), ObjectUtil.isEmpty(objValue) ? null : field.get(obj));
}
} catch (Exception e) {
e.printStackTrace();
}
return map;
}
/**
* Map转成实体对象
* @param map map实体对象包含属性
* @param clazz 实体对象类型
* @return
*/
public static Object mapToObject(Map<String, Object> map, Class<T> clazz) {
if (map == null) {
return null;
}
Object obj = null;
try {
obj = clazz.newInstance();
Field[] fields = obj.getClass().getDeclaredFields();
for (Field field : fields) {
int mod = field.getModifiers();
if (Modifier.isStatic(mod) || Modifier.isFinal(mod)) {
continue;
}
field.setAccessible(true);
field.set(obj, map.get(field.getName()));
}
} catch (Exception e) {
e.printStackTrace();
}
return obj;
}
/**
*
* @description: Map转实体类
* @param <T>
* @param map 需要初始化的数据,key字段必须与实体类的成员名字一样,否则赋值为空
* @param entity 需要转化成的实体类
* @return
*/
public static <T> T mapToEntity(Map<String, Object> map, Class<T> entity) {
T t = null;
try {
t = entity.newInstance();
for (Field field : entity.getDeclaredFields()) {
if (map.containsKey(field.getName())) {
boolean flag = field.isAccessible();
field.setAccessible(true);
Object object = map.get(field.getName());
if (object != null && field.getType().isAssignableFrom(object.getClass())) {
field.set(t, object);
}
field.setAccessible(flag);
}
}
return t;
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
return t;
}
/**
*
* @description: 实体类转Map
* @param object
* @return
*/
public static Map<String, Object> entityToMap(Object object) {
Map<String, Object> map = new HashMap<>();
for (Field field : object.getClass().getDeclaredFields()) {
try {
boolean flag = field.isAccessible();
field.setAccessible(true);
Object o = field.get(object);
map.put(field.getName(), o);
field.setAccessible(flag);
} catch (Exception e) {
e.printStackTrace();
}
}
return map;
}
public static void main(String[] args) {
// TODO Auto-generated method class
实体类(TestClass) classes = new 实体类TestClass();
classes.setActCount("sdfsdaf");
Map<String, Object> map = objectToMap(classes);
System.out.println(map);
System.out.println("***********************************************");
Map<String, Object> map1 = beanToMap(classes);
System.out.println(map1);
System.out.println("***********************************************");
Map<String, Object> map2 = JSON.parseObject(JSON.toJSONString(classes, false), Map.class);
System.out.println(map2);
System.out.println("***********************************************");
Map<String, Object> map3 = entityToMap(classes);
System.out.println(map3);
System.out.println("***********************************************");
}
}
运行结果:
{stockDays=null, pageSize=0, actCount=sdfsdaf, pageNum=0}
***********************************************
{pageSize=0, actCount=sdfsdaf, pageNum=0}
***********************************************
{pageSize=0, actCount=sdfsdaf, pageNum=0}
***********************************************
{stockDays=null, pageSize=0, actCount=sdfsdaf, pageNum=0}
***********************************************
总结一下:
如果实体类转Map,使用Class 转JSON,再转Map。转出的Map和原来的实体类对比一下,会发现实体类中空的内容,在Map中是没有的。如果想要实体类中内容为空的字段也转成Map的内容,需要调用Map<String, Object> objectToMap(Object obj);