BeanUtils之对象实体类转HashMap
package com.example.demo.common.Utils;
import org.apache.catalina.util.Introspection;
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;
// 实体工具类
public class BeanUtils {
/**
* 把实体类变成map。
* @param bean 传入一个bean
* @return hashMap
* @throws IllegalStateException
* @throws InvocationTargetException
* @throws IntrospectionException
*/
public static Map<String,Object> beanToMap(Object bean) throws InvocationTargetException, IntrospectionException, IllegalAccessException {
Map<String,Object> retrunMap = new HashMap<>();
BeanInfo beanInfo = Introspector.getBeanInfo(bean.getClass());
PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
for (int i=0;i<propertyDescriptors.length;++i){
PropertyDescriptor descriptor = propertyDescriptors[i];
String propertyName = descriptor.getName();
if (!propertyName.equals("class")){
Method readMethod = descriptor.getReadMethod();
Object result = readMethod.invoke(bean);
if (result!=null){
retrunMap.put(propertyName,result);
}
}
}
return retrunMap;
}
}