package com.siang.util; import java.beans.BeanInfo; import java.beans.Introspector; import java.beans.PropertyDescriptor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.HashMap; import java.util.Map; import org.apache.commons.beanutils.BeanUtils; import org.apache.commons.beanutils.ConvertUtils; import org.apache.commons.beanutils.converters.DateConverter; public class BeanCopy { static { ConvertUtils.register(new DateConverter(), java.util.Date.class); ConvertUtils.register(new DateConverter(), java.sql.Date.class); } /** * @1 map to bean * @2 bean to bean * @3 bean to map */ public static void copyProperties(Object dest, Object orig){ try { if (dest instanceof Map ) {//3 bean to map transBean2Map((Map)dest,orig); }else { BeanUtils.copyProperties(dest, orig); } } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } } /** * model to map * @param orig */ private static void transBean2Map(Map dest , Object orig) { try { BeanInfo beanInfo = Introspector.getBeanInfo(orig.getClass()); PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors(); for (PropertyDescriptor property : propertyDescriptors) { String key = property.getName(); // 过滤class属性 if (!key.equals("class")) { // 得到property对应的getter方法 Method getter = property.getReadMethod(); Object value = getter.invoke(orig); dest.put(key, value); } } } catch (Exception e) { System.out.println("transBean2Map Error " + e); } } public static void main(String[] args) { Map<String, Object> map= new HashMap<String, Object>(); map.put("id", "1"); map.put("name", "穿林渡水"); User user = new User(); copyProperties(user , map); System.out.println(user.getId() + "---" + user.getName()); User user1 = new User(); copyProperties(user1 , user); System.out.println(user1.getId()); Map<String, Object> map2= new HashMap<String, Object>(); copyProperties(map2 , user); System.out.println(map2); } }