From 47ffe22e1d949f9e934642a5b7fec89b09dfaf50 Mon Sep 17 00:00:00 2001 From: wenc000 <450292408@qq.com> Date: Fri, 15 Nov 2019 11:36:04 +0800 Subject: [PATCH] =?UTF-8?q?=E6=96=B0=E5=A2=9Emap=E8=BD=ACbean=E7=9A=84?= =?UTF-8?q?=E6=96=B9=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../java/com/cm/common/utils/HashMapUtil.java | 33 +++++++++++++++++++ 1 file changed, 33 insertions(+) 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; + } + }