03-封裝BeanUtil工具類(javabean轉map和map轉javabean物件)
阿新 • • 發佈:2018-11-19
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) } }