转自:http://blog.csdn.net/cuidiwhere/article/details/8130434
因为在写接口的时候,经常会将request的数据转成map,然后再map.get(key),bean.setKey(value);每次这样比较麻烦;
写一个工具类,直接进行将Map和Bean进行转换
转换的时候,类型要匹配,比如map中age属性是Integer,而Bean中age是String,那么该属性就会转换失败;只能转换前进行预处理,就是把map中的age从Integer转成String
下面是代码:
//map2bean public static void mapToBean(Map<String,Object> map, Object object){ try{ BeanInfo beanInfo = Introspector.getBeanInfo(object.getClass()); PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors(); for(PropertyDescriptor p : propertyDescriptors){ String key = p.getName(); if(map.containsKey(key)){ Object value = map.get(key); Method setter = p.getWriteMethod(); setter.invoke(object,value); } } } catch (Exception e) { e.printStackTrace(); } } //bean2map public static Map<String,Object> BeanToMap(Object object) { if (object == null) { return null; } Map<String, Object> map = new HashMap<>(); try { BeanInfo beanInfo = Introspector.getBeanInfo(object.getClass()); PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors(); for (PropertyDescriptor p : propertyDescriptors) { String key = p.getName(); //过滤class属性 if (!key.equals("class")) { Method getter = p.getReadMethod(); Object value = getter.invoke(object, key); map.put(key, value); } } } catch (Exception e) { e.printStackTrace(); } return map; }