import java.beans.PropertyDescriptor;
import java.io.Serializable;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.lang3.reflect.FieldUtils;
public class MapUtils {
/**
* 将Map数据填充到指定Bean对象中
*
* @param bean
* @param map
*/
public static void applyToObject(Object bean, Map<String, Serializable> map) {
try {
for (Entry<String, ?> entry : map.entrySet()) {
PropertyUtils.setProperty(bean, entry.getKey(), entry.getValue());
}
} catch (Throwable t) {
throw new IllegalArgumentException(t);
}
}
/**
* map中的数据更新到指定对象同名属性中
*
* @param target
* @param map
*/
@SuppressWarnings({"rawtypes", "unchecked"})
public static void updateFromMap(Object target, Map<String, ?> map) {
for (Entry<String, ?> entry : map.entrySet()) {
try {
Object value = entry.getValue();
String fieldName = entry.getKey();
Field field = FieldUtils.getField(target.getClass(), fieldName);
if (value != null && field != null) {
// 处理枚举
Class fieldClass = field.getType();
if (fieldClass.isEnum())
value = Enum.valueOf(fieldClass, value.toString());
field.set(target, value);
}
} catch (IllegalAccessException e) {
throw new IllegalArgumentException(e);
}
}
}
/**
* 指定对象转换为Map<String,Object>;
*
* @param target
* @return
*/
public static Map<String, Object> convertToMap(Object target) {
try {
Map<String, Object> map = new HashMap<String, Object>();
PropertyDescriptor pds[] = PropertyUtils.getPropertyDescriptors(target);
for (PropertyDescriptor pd : pds) {
if (pd.getName().equals("class"))
continue;
map.put(pd.getName(), pd.getReadMethod().invoke(target));
}
return map;
} catch (Exception e) {
throw new IllegalArgumentException(e);
}
}
/**
* 指定对象转换为Map<String,Serializable>;
*
* @param bean
* @return
*/
public static Map<String, Serializable> convertToMapWithSerializable(Object bean) {
try {
Map<String, Serializable> result = new TreeMap<String, Serializable>();
for (PropertyDescriptor pd : PropertyUtils.getPropertyDescriptors(bean.getClass())) {
if (pd.getName().equals("class"))
continue;
Object value = PropertyUtils.getProperty(bean, pd.getName());
if (value instanceof Serializable)
result.put(pd.getName(), (Serializable) value);
}
return result;
} catch (Throwable t) {
throw new IllegalArgumentException(t);
}
}
}