JAVA Map转换为实体类和实体类转换为MAP

朴灿烈づ我的快乐病毒、 2022-05-22 13:20 627阅读 0赞

package com.ruiguang.tools;

import java.beans.BeanInfo;
import java.beans.IntrospectionException;
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.lang.reflect.Modifier;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class JavaBeanUtil {
private static Logger logger = LoggerFactory.getLogger(JavaBeanUtil.class);

  1. /\*\*
  2. \* 实体类转map
  3. \* @param obj
  4. \* @return
  5. \*/
  6. public static Map<String, Object> convertBeanToMap(Object obj) \{
  7. if (obj == null) \{
  8. return null;
  9. \}
  10. Map<String, Object> map = new HashMap<String, Object>();
  11. try \{
  12. BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
  13. PropertyDescriptor\[\] propertyDescriptors = beanInfo.getPropertyDescriptors();
  14. for (PropertyDescriptor property : propertyDescriptors) \{
  15. String key = property.getName();
  16. // 过滤class属性
  17. if (!key.equals("class")) \{
  18. // 得到property对应的getter方法
  19. Method getter = property.getReadMethod();
  20. Object value = getter.invoke(obj);
  21. if(null==value)\{
  22. map.put(key,"");
  23. \}else\{
  24. map.put(key,value);
  25. \}
  26. \}
  27. \}
  28. \} catch (Exception e) \{
  29. logger.error("convertBean2Map Error \{\}" ,e);
  30. \}
  31. return map;
  32. \}
  33. /\*\*
  34. \* map 转实体类
  35. \* @param clazz
  36. \* @param map
  37. \* @param <T>
  38. \* @return
  39. \*/
  40. public static <T> T convertMapToBean(Class<T> clazz, Map<String,Object> map) \{
  41. T obj = null;
  42. try \{
  43. BeanInfo beanInfo = Introspector.getBeanInfo(clazz);
  44. obj = clazz.newInstance(); // 创建 JavaBean 对象
  45. // 给 JavaBean 对象的属性赋值
  46. PropertyDescriptor\[\] propertyDescriptors = beanInfo.getPropertyDescriptors();
  47. for (int i = 0; i < propertyDescriptors.length; i++) \{
  48. PropertyDescriptor descriptor = propertyDescriptors\[i\];
  49. String propertyName = descriptor.getName();
  50. if (map.containsKey(propertyName)) \{
  51. // 下面一句可以 try 起来,这样当一个属性赋值失败的时候就不会影响其他属性赋值。
  52. Object value = map.get(propertyName);
  53. if ("".equals(value)) \{
  54. value = null;
  55. \}
  56. Object\[\] args = new Object\[1\];
  57. args\[0\] = value;
  58. descriptor.getWriteMethod().invoke(obj, args);
  59. \}
  60. \}
  61. \} catch (IllegalAccessException e) \{
  62. logger.error("convertMapToBean 实例化JavaBean失败 Error\{\}" ,e);
  63. \} catch (IntrospectionException e) \{
  64. logger.error("convertMapToBean 分析类属性失败 Error\{\}" ,e);
  65. \} catch (IllegalArgumentException e) \{
  66. logger.error("convertMapToBean 映射错误 Error\{\}" ,e);
  67. \} catch (InstantiationException e) \{
  68. logger.error("convertMapToBean 实例化 JavaBean 失败 Error\{\}" ,e);
  69. \}catch (InvocationTargetException e)\{
  70. logger.error("convertMapToBean字段映射失败 Error\{\}" ,e);
  71. \}catch (Exception e)\{
  72. logger.error("convertMapToBean Error\{\}" ,e);
  73. \}
  74. return (T) obj;
  75. \}
  76. //将map通过反射转化为实体
  77. public static Object MapToModel(Map<String,Object> map,Object o) throws Exception\{
  78. if (!map.isEmpty()) \{
  79. for (String k : map.keySet()) \{
  80. Object v =null;
  81. if (!k.isEmpty()) \{
  82. v = map.get(k);
  83. \}
  84. Field\[\] fields = null;
  85. fields = o.getClass().getDeclaredFields();
  86. String clzName = o.getClass().getSimpleName();
  87. for (Field field : fields) \{
  88. int mod = field.getModifiers();
  89. if (field.getName().toUpperCase().equals(k.toUpperCase())) \{
  90. field.setAccessible(true);
  91. //region--进行类型判断
  92. String type=field.getType().toString();
  93. if (type.endsWith("String"))\{
  94. if (v!=null)\{
  95. v=v.toString();
  96. \}else \{
  97. v="";
  98. \}
  99. \}
  100. if (type.endsWith("Date"))\{
  101. v=new Date(v.toString());
  102. \}
  103. if (type.endsWith("Boolean"))\{
  104. v=Boolean.getBoolean(v.toString());
  105. \}
  106. if (type.endsWith("int"))\{
  107. v=new Integer(v.toString());
  108. \}
  109. if (type.endsWith("Long"))\{
  110. v=new Long(v.toString());
  111. \}
  112. //endregion
  113. field.set(o, v);
  114. \}
  115. \}
  116. \}
  117. \}
  118. return o;
  119. \}
  120. /\*\*
  121. \* 实体对象转成Map
  122. \* @param obj 实体对象
  123. \* @return
  124. \*/
  125. public static Map<String, Object> object2Map(Object obj) \{
  126. Map<String, Object> map = new HashMap<>();
  127. if (obj == null) \{
  128. return map;
  129. \}
  130. Class clazz = obj.getClass();
  131. Field\[\] fields = clazz.getDeclaredFields();
  132. try \{
  133. for (Field field : fields) \{
  134. field.setAccessible(true);
  135. map.put(field.getName(), field.get(obj));
  136. \}
  137. \} catch (Exception e) \{
  138. e.printStackTrace();
  139. \}
  140. return map;
  141. \}
  142. /\*\*
  143. \* Map转成实体对象
  144. \* @param map map实体对象包含属性
  145. \* @param clazz 实体对象类型
  146. \* @return
  147. \*/
  148. public static Object map2Object(Map<String, Object> map, Class<?> clazz) \{
  149. if (map == null) \{
  150. return null;
  151. \}
  152. Object obj = null;
  153. try \{
  154. obj = clazz.newInstance();
  155. Field\[\] fields = obj.getClass().getDeclaredFields();
  156. for (Field field : fields) \{
  157. int mod = field.getModifiers();
  158. if (Modifier.isStatic(mod) || Modifier.isFinal(mod)) \{
  159. continue;
  160. \}
  161. field.setAccessible(true);
  162. field.set(obj, map.get(field.getName()));
  163. \}
  164. \} catch (Exception e) \{
  165. e.printStackTrace();
  166. \}
  167. return obj;
  168. \}
  169. public static void main(String\[\] args) \{
  170. // TODO Auto-generated method stub
  171. /\*Student s = new Student();
  172. s.setUserName("ZHH");
  173. s.setAge("24");
  174. System.out.println(object2Map(s));
  175. Map<String, Object> map = new HashMap<>();
  176. map.put("userName", "zhh");
  177. map.put("age", "24");
  178. System.out.println(map2Object(map, Student.class));\*/
  179. \}

}

发表评论

表情:
评论列表 (有 0 条评论,627人围观)

还没有评论,来说两句吧...

相关阅读