新增map转bean的方法

This commit is contained in:
wenc000 2019-11-15 11:36:04 +08:00
parent 2dbb18283e
commit 47ffe22e1d

View File

@ -1,9 +1,14 @@
package com.cm.common.utils;
import com.cm.common.pojo.vos.push.PushMessageVO;
import org.apache.commons.lang3.StringUtils;
import javax.servlet.http.HttpServletRequest;
import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Enumeration;
import java.util.HashMap;
@ -162,4 +167,32 @@ public class HashMapUtil {
return result;
}
/**
* map转obj需要map的key和obj的属性对应要有标准的set方法
*
* @param map
* @param clazz
* @return
*/
public static <T> T mapToBean(Map<String, Object> map, Class<T> clazz) {
try {
Field[] fields = clazz.getDeclaredFields();
Object instanceObj = clazz.newInstance();
for (Map.Entry<String, Object> kvs : map.entrySet()) {
for (Field field : fields) {
String fieldName = field.getName();
if (StringUtils.equals(fieldName, kvs.getKey())) {
Method method = clazz.getMethod("set" + WStringUtil.firstToUpper(fieldName), field.getType());
method.invoke(instanceObj, kvs.getValue());
break;
}
}
}
return clazz.cast(instanceObj);
} catch (InstantiationException | IllegalAccessException | NoSuchMethodException | InvocationTargetException e) {
e.printStackTrace();
}
return null;
}
}