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 }
llh