新增map转bean的方法
This commit is contained in:
parent
2dbb18283e
commit
47ffe22e1d
@ -1,9 +1,14 @@
|
|||||||
package com.cm.common.utils;
|
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 javax.servlet.http.HttpServletRequest;
|
||||||
import java.beans.BeanInfo;
|
import java.beans.BeanInfo;
|
||||||
import java.beans.Introspector;
|
import java.beans.Introspector;
|
||||||
import java.beans.PropertyDescriptor;
|
import java.beans.PropertyDescriptor;
|
||||||
|
import java.lang.reflect.Field;
|
||||||
|
import java.lang.reflect.InvocationTargetException;
|
||||||
import java.lang.reflect.Method;
|
import java.lang.reflect.Method;
|
||||||
import java.util.Enumeration;
|
import java.util.Enumeration;
|
||||||
import java.util.HashMap;
|
import java.util.HashMap;
|
||||||
@ -162,4 +167,32 @@ public class HashMapUtil {
|
|||||||
return result;
|
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;
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
Loading…
Reference in New Issue
Block a user