diff --git a/cloud-common/src/main/java/com/cm/common/utils/HashMapUtil.java b/cloud-common/src/main/java/com/cm/common/utils/HashMapUtil.java index 9ffd290..62d04e3 100644 --- a/cloud-common/src/main/java/com/cm/common/utils/HashMapUtil.java +++ b/cloud-common/src/main/java/com/cm/common/utils/HashMapUtil.java @@ -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 mapToBean(Map map, Class clazz) { + try { + Field[] fields = clazz.getDeclaredFields(); + Object instanceObj = clazz.newInstance(); + for (Map.Entry 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; + } + }