package com.oa.test; import java.beans.BeanInfo; import java.beans.IntrospectionException; import java.beans.Introspector; import java.beans.PropertyDescriptor; import java.util.HashMap; import java.util.Map; public class BeanUtil { /** * 將JavaBean對象封裝到Map集合當中 * @param bean * @return * @throws Exception */ public static Map<String, Object> bean2map(Object bean) throws Exception { //創建Map集合對象 Map<String,Object> map=new HashMap<String, Object>(); //獲取對象字節碼信息,不要Object的屬性 BeanInfo beanInfo = Introspector.getBeanInfo(bean.getClass(),Object.class); //獲取bean對象中的所有屬性 PropertyDescriptor[] list = beanInfo.getPropertyDescriptors(); for (PropertyDescriptor pd : list) { String key = pd.getName();//獲取屬性名 Object value = pd.getReadMethod().invoke(bean);//調用getter()方法,獲取內容 map.put(key, value);//增加到map集合當中 } return map; } /** * 將Map集合中的數據封裝到JavaBean對象中 * @param map 集合 * @param classType 封裝javabean對象 * @throws Exception */ public static <T> T map2bean(Map<String, Object> map,Class<T> classType) throws Exception { //采用反射動態創建對象 T obj = classType.newInstance(); //獲取對象字節碼信息,不要Object的屬性 BeanInfo beanInfo = Introspector.getBeanInfo(classType,Object.class); //獲取bean對象中的所有屬性 PropertyDescriptor[] list = beanInfo.getPropertyDescriptors(); for (PropertyDescriptor pd : list) { String key = pd.getName(); //獲取屬性名 Object value=map.get(key); //獲取屬性值 pd.getWriteMethod().invoke(obj, value);//調用屬性setter()方法,設置到javabean對象當中 } return obj; } }
測試代碼如下
package com.oa.test; import java.util.Map; import com.oa.domain.User; public class Demo3 { /** * 劉詩華 * @param args * @throws Exception */ public static void main(String[] args) throws Exception { // User(id=28, userName=劉詩華, password=123456) User user=new User(28,"劉詩華","123456"); //將JavaBean集合轉換成Map集合 Map<String, Object> m = BeanUtil.bean2map(user); System.out.println(m); //{id=28, userName=劉詩華, password=123456} //將Map集合轉換JavaBean對象 User o = BeanUtil.map2bean(m, User.class); System.out.println(o); //User(id=28, userName=劉詩華, password=123456) } }