话不多说,直接上工具类代码
public static <T> T convertMapBean(Map<String, Object> map, Class<T> T)
throws Exception
{
if (map == null || map.size() == 0)
{
return null;
}
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);
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;
}