JAvaオブジェクトをmapに、mapオブジェクトツールクラスに変換
8206 ワード
1 /**
2 * map
3 *
4 * @param map
5 * @param beanClass
6 * @return
7 * @throws Exception
8 */
9 public static Object mapToObject(Map map, Class> beanClass) throws Exception {
10 if (map == null)
11 return null;
12
13 Object obj = beanClass.newInstance();
14
15 BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
16 PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
17 for (PropertyDescriptor property : propertyDescriptors) {
18 Method setter = property.getWriteMethod();
19 if (setter != null) {
20 setter.invoke(obj, map.get(property.getName()));
21 }
22 }
23
24 return obj;
25 }
26
27 /**
28 * map
29 *
30 * @param obj
31 * @return
32 * @throws Exception
33 */
34 public static Map obj2Map(Object obj) {
35
36 Map map = new HashMap();
37 // System.out.println(obj.getClass());
38 // f
39 Field[] fields = obj.getClass().getDeclaredFields();
40 for (int i = 0, len = fields.length; i < len; i++) {
41 String varName = fields[i].getName();
42 varName = varName.toLowerCase();// key ,
43 try {
44 //
45 boolean accessFlag = fields[i].isAccessible();
46 //
47 fields[i].setAccessible(true);
48 // f fields[i]
49 Object o = fields[i].get(obj);
50 if (o != null)
51 map.put(varName, o.toString());
52 // System.out.println(" :" + varName + " = " + o);
53 //
54 fields[i].setAccessible(accessFlag);
55 } catch (IllegalArgumentException ex) {
56 ex.printStackTrace();
57 } catch (IllegalAccessException ex) {
58 ex.printStackTrace();
59 }
60 }
61 return map;
62 }
転載先:https://www.cnblogs.com/javallh/p/10477175.html