① 类型转换

1 map 与 Object 相互转换 

 

 1 import java.lang.reflect.Field;
 2 import java.lang.reflect.Modifier;
 3 import java.util.HashMap;
 4 import java.util.Map;
 5 /**
 6  *  方式一:反射
 7  *  方式二:Apache  commons-beanutils工具包
 8  */
 9 public class ObjectConvertUtil {
10 
11 
12     /**
13      * 【反射方式实现】
14      *  1、object转换成map
15      * @param obj
16      * @return
17      * @throws Exception
18      */
19     public static Map<String, Object> obj2Map(Object obj) throws Exception {
20         Map<String, Object> map = new HashMap<String, Object>();
21         Field[] fields = obj.getClass().getDeclaredFields();
22         for (Field field : fields) {
23             field.setAccessible(true);
24             map.put(field.getName(), field.get(obj));
25         }
26         return map;
27     }
28 
29     /**
30      * 【反射方式实现】
31      *  2、map转换为object
32      * @param map
33      * @param clz
34      * @return
35      * @throws Exception
36      */
37     public static Object map2Obj(Map<String, Object> map, Class<?> clz) throws Exception {
38         Object obj = clz.newInstance();
39         Field[] declaredFields = obj.getClass().getDeclaredFields();
40         for (Field field : declaredFields) {
41             int mod = field.getModifiers();
42             if (Modifier.isStatic(mod) || Modifier.isFinal(mod)) {
43                 continue;
44             }
45             field.setAccessible(true);
46             field.set(obj, map.get(field.getName()));
47         }
48         return obj;
49     }
50 
51 
52 
53     /**
54      * 【使用Apache中的BeanUtils类,导入commons-beanutils包。】
55      *  1、map转换为object
56      * @param map
57      * @param beanClass
58      * @return
59      * @throws Exception
60      */
61     public static Object mapToObject(Map<String, Object> map, Class<?> beanClass)
62             throws Exception {
63         if (map == null) {
64             return null;
65 
66         }
67         Object obj = beanClass.newInstance();
68         org.apache.commons.beanutils.BeanUtils.populate(obj, map);
69         return obj;
70     }
71 
72 
73     /**
74      * 【使用Apache中的BeanUtils类,导入commons-beanutils包。】
75      *  2、object转换为map
76      * @param obj
77      * @return
78      */
79     public static Map<?, ?> objectToMap(Object obj) {
80         if (obj == null) {
81             return null;
82         }
83         return new org.apache.commons.beanutils.BeanMap(obj);
84     }
85 
86 
87 }

 

2 map 与 JSON 相互转换

 

3 Object 与 JSON 相互转换

posted @ 2019-07-09 15:17  zrzhen  阅读(112)  评论(0)    收藏  举报