/** * 将对象装换为map * @param bean * @return */ public static <T> Map<String, Object> beanToMap(T bean) { Map<String, Object> map = new HashMap(); if (bean != null) { BeanMap beanMap = BeanMap.create(bean); for (Object key : beanMap.keySet()) { Object obj =beanMap.get(key); if (!org.springframework.util.StringUtils.isEmpty(obj)) { if(obj instanceof Date || obj instanceof Calendar){ map.put(key + "",formtDate(obj,"yyyy-MM-dd HH:mm:ss")); }else{ map.put(key + "", beanMap.get(key)); } } } } return map; } /** * * @param date * @param pattern * @return */ public static String formtDate(Object date, String pattern) { if(date == null){ return ""; } if(date instanceof Calendar){ date = ((Calendar) date).getTime(); } if(pattern == null || pattern.trim().equals("")){ pattern = "yyyy-MM-dd HH:mm:ss"; } return new SimpleDateFormat(pattern).format(date); } /** * 将map装换为javabean对象 * * @param map * @param bean * @return */ public static <T> T mapToBean(Map<String, Object> map, T bean) { BeanMap beanMap = BeanMap.create(bean); beanMap.putAll(map); return bean; }
调用:其中DataUtils为以上方法的工具类
public void saveNames(Map<String,Object> map) { Student record = new Strdent(); DataUtils.mapToBean(map,record);//此时map中Student类型对象可用属性已赋值给record; }
public void saveNames(Student record) { Map<String,Object> param = DataUtils.beanToMap(record); }