import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class MapUtils {
private static Logger logger = LoggerFactory.getLogger(MapUtils.class);
/**
*
* bean對象轉mapObj
* @param obj 待轉換bean對象
* @return mapObj
*/
public static Map<String, Object> beanToMapObj(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);
map.put(key, value);
}
}
} catch (Exception e) {
logger.error("beanToMapObj Error:{}", e.getMessage(), e);
}
return map;
}
/**
*
* bean對象轉mapStr
* @param obj 待轉換bean對象
* @return mapStr
*/
public static Map<String, String> beanToMapStr(Object obj) {
if (obj == null) {
return null;
}
Map<String, String> map = new HashMap<String, String>();
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();
String value = (String) getter.invoke(obj);
map.put(key, value);
}
}
} catch (Exception e) {
logger.error("beanToMapStr Error:{}", e.getMessage(), e);
}
return map;
}
/**
*
* 利用反射將mapObj集合封裝成bean對象
* @param map 待轉換mapObj
* @param beanType 對象中的object類型
* @return
* @throws Exception
*/
@SuppressWarnings("unchecked")
public static <T> T mapObjToBean(Map<String, Object> map, Class<?> beanType) throws Exception {
Object obj = beanType.newInstance();
if (map != null && !map.isEmpty() && map.size() > 0) {
for (Map.Entry<String, Object> entry : map.entrySet()) {
String propertyName = entry.getKey(); // 屬性名
Object value = entry.getValue(); // 屬性值
String setMethodName = "set" + propertyName.substring(0, 1).toUpperCase() + propertyName.substring(1);
Field field = getClassField(beanType, propertyName); // 獲取和map的key匹配的屬性名稱
if (field == null) {
continue;
}
Class<?> fieldTypeClass = field.getType();
value = convertValType(value, fieldTypeClass);
try {
beanType.getMethod(setMethodName, field.getType()).invoke(obj, value);
} catch (NoSuchMethodException e) {
logger.error("mapToBean Error:{}", e.getMessage(), e);
}
}
}
return (T) obj;
}
/**
*
* 利用反射將mapStr集合封裝成bean對象
* @param map 待轉換mapStr
* @param beanType 對象中的object類型
* @return
* @throws Exception
*/
@SuppressWarnings("unchecked")
public static <T> T mapStrToBean(Map<String, String> map, Class<?> beanType) throws Exception {
Object obj = beanType.newInstance();
if (map != null && !map.isEmpty() && map.size() > 0) {
for (Map.Entry<String, String> entry : map.entrySet()) {
String propertyName = entry.getKey(); // 屬性名
Object value = entry.getValue(); // 屬性值
String setMethodName = "set" + propertyName.substring(0, 1).toUpperCase() + propertyName.substring(1);
Field field = getClassField(beanType, propertyName); // 獲取和map的key匹配的屬性名稱
if (field == null) {
continue;
}
Class<?> fieldTypeClass = field.getType();
value = convertValType(value, fieldTypeClass);
try {
beanType.getMethod(setMethodName, field.getType()).invoke(obj, value);
} catch (NoSuchMethodException e) {
logger.error("mapStrToBean Error:{}", e.getMessage(), e);
}
}
}
return (T) obj;
}
/**
*
* 根據給定對象類匹配對象中的特定字段
* @param clazz 對象類型
* @param fieldName 字段名稱
* @return
*/
private static Field getClassField(Class<?> clazz, String fieldName) {
if (Object.class.getName().equals(clazz.getName())) {
return null;
}
Field[] declaredFields = clazz.getDeclaredFields();
for (Field field : declaredFields) {
if (field.getName().equals(fieldName)) {
return field;
}
}
Class<?> superClass = clazz.getSuperclass(); // 如果該類還有父類,將父類對象中的字段也取出
if (superClass != null) { // 遞歸獲取
return getClassField(superClass, fieldName);
}
return null;
}
/**
*
* 將map的value值轉爲實體類中字段類型匹配的方法
* @param value 字段值
* @param fieldTypeClass 字段類型
* @return
*/
private static Object convertValType(Object value, Class<?> fieldTypeClass) {
Object retVal = null;
if (Long.class.getName().equals(fieldTypeClass.getName()) || long.class.getName().equals(fieldTypeClass.getName())) {
retVal = Long.parseLong(value.toString());
} else if (Integer.class.getName().equals(fieldTypeClass.getName()) || int.class.getName().equals(fieldTypeClass.getName())) {
retVal = Integer.parseInt(value.toString());
} else if (Float.class.getName().equals(fieldTypeClass.getName()) || float.class.getName().equals(fieldTypeClass.getName())) {
retVal = Float.parseFloat(value.toString());
} else if (Double.class.getName().equals(fieldTypeClass.getName()) || double.class.getName().equals(fieldTypeClass.getName())) {
retVal = Double.parseDouble(value.toString());
} else {
retVal = value;
}
return retVal;
}
}
利用反射實現MapStr、MapObj與bean之間的轉換
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.