java將對象轉map,map轉對象工具類


 1  /**
 2      * 將map轉換為一個對象
 3      *
 4      * @param map
 5      * @param beanClass
 6      * @return
 7      * @throws Exception
 8      */
 9     public static Object mapToObject(Map<String, String> 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<String, String> obj2Map(Object obj) {
35 
36         Map<String, String> map = new HashMap<String, String>();
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     }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM