将 Map对象转化为JavaBean
/**
* 将 Map对象转化为JavaBean
* @param map
* @param T
* @return
* @throws Exception
* @Email:CloverAn@aliyun.com
*/
public static <T> T convertMapBean(Map<String, Object> map, Class<T> T)
throws Exception
{
if (map == null || map.size() == 0)
{
return null;
}
//获取map中所有的key值,全部更新成大写,添加到keys集合中,与mybatis中驼峰命名匹配
Object mvalue = null;
Map<String, Object> newMap = new HashMap<>(16);
Iterator<Map.Entry<String, Object>> it = map.entrySet().iterator();
while(it.hasNext()){
String key = it.next().getKey();
mvalue = map.get(key);
/* if (key.indexOf(CharacterConstant.UNDERLINE) != -1)
{
key = key.replaceAll(CharacterConstant.UNDERLINE, "");
}*/
key = key.replaceAll("\\.","");
key = key.replaceAll("_","");
newMap.put(key.toUpperCase(Locale.US), mvalue);
}
BeanInfo beanInfo = Introspector.getBeanInfo(T);
T bean = T.newInstance();
PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
for (int i = 0, n = propertyDescriptors.length; i < n; i++)
{
PropertyDescriptor descriptor = propertyDescriptors[i];
String propertyName = descriptor.getName();
String upperPropertyName = propertyName.toUpperCase();
if (newMap.keySet().contains(upperPropertyName))
{
Object value = newMap.get(upperPropertyName);
//这个方法不会报参数类型不匹配的错误。
BeanUtils.copyProperty(bean, propertyName, value);
}
}
return bean;
}