平時我們常會遇到Bean對象和Map的轉換,對於字段比較少並且結構簡單的Bean對象和Map的轉換,常規做法就是逐個去set屬性和值,或者逐個put屬性和值,但是如果對於字段比較多或者嵌套結構複雜的Bean對象和Map轉換,常規做法就遠遠力不從心了,那麼我們就需要封裝一個公共的高效的泛型工具類去進行轉換。筆者結合平時的編碼經驗積累,經過整理,本案例給大家分享5種方式實現Bean對象和Map的轉換,本案例基於BeanUtils.populate(bean, map)和JDK自帶的反射機制,廢話不多時,直接上代碼。
準備工作:先在pom文件中添加org.apache.commons的依賴,如下所示:
<dependency>
<groupId>commons-beanutils</groupId>
<artifactId>commons-beanutils</artifactId>
</dependency>
工具類的5種具體實現方式:
package com.shsc.base.data.common.utils;
import org.apache.commons.beanutils.BeanUtils;
import com.shsc.base.data.common.mapper.entity.CustomerProduct;
import com.shsc.base.data.common.mapper.entity.ProductPic;
import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class BeanConverterUtils {
public static void main(String[] args) {
// TODO Auto-generated method stub
Map<String, Object> map = new HashMap<String, Object>();
List <ProductPic> pics = new ArrayList<ProductPic>();
ProductPic pic = new ProductPic();
pic.setAttachmentId("12324324353464747");
pics.add(pic);
map.put("customerId", "111");
map.put("productId", "222");
map.put("pics", pics);
CustomerProduct c = new CustomerProduct();
try {
// map2Bean(map,c);
// mapToBean(map,c.getClass());
map2JavaBean(map,c);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* Map轉換Bean對象方式一:使用apache.commons.beanutils.BeanUtils實現(需在pom文件中添加依賴)
* 使用泛型免去了類型轉換的麻煩。
* @param <T>
* @param map
* @param beanClass
* @return
*/
public static <T> T map2Bean(Map<String, Object> map, T t) {
try {
BeanUtils.populate(t, map);
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return t;
}
/**
* Map轉換Bean對象方式二:使用apache.commons.beanutils.BeanUtils實現(需在pom文件中添加依賴)
* @param <T>
* @param map
* @param beanClass
* @return
*/
public static <T> T mapToBean(Map<String, Object> map, Class<T> beanClass){
T bean = null;
try {
bean = beanClass.newInstance();
BeanUtils.populate(bean, map);
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
return bean;
}
/**
* Map轉換Bean對象方式三(基於JDK實現)
* @param map
* @param t
* @param <T>
* @return
*/
public static <T> T map2JavaBean(Map<String, Object> map, T t) {
if(map == null || t == null) {
return null;
}
try {
BeanInfo beanInfo = Introspector.getBeanInfo(t.getClass());
PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors();
for(PropertyDescriptor pd : pds) {
String key = pd.getName();
if(map.containsKey(key)) {
Object value = map.get(key);
Method setter = pd.getWriteMethod();
setter.invoke(t, value);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return t;
}
/**
* Bean對象轉換Map方式一(基於JDK實現)
* @param obj
* @return
*/
public static Map<String, Object> bean2Map(Object obj)throws Exception{
Map<String, Object> map = new HashMap<String, Object>();
Class<?> clazz = obj.getClass();
Field[] fields = clazz.getDeclaredFields();
for (Field field : fields) {
PropertyDescriptor pd = new PropertyDescriptor(field.getName(), clazz);
Method getMethod = pd.getReadMethod();
Object o = getMethod.invoke(obj);
map.put(field.getName(), o);
}
return map;
}
/**
* Bean對象轉換Map方式二(基於JDK實現)
* @param obj
* @return
*/
public static <T> Map<String, Object> beanToMap(T bean)throws Exception{
if(bean == null) {
return null;
}
Map<String, Object> map = new HashMap<String, Object>();
BeanInfo beanInfo = Introspector.getBeanInfo(bean.getClass());
PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors();
for(PropertyDescriptor pd : pds) {
String key = pd.getName();
Method getMethod = pd.getWriteMethod();
Object o = getMethod.invoke(bean);
map.put(key, o);
}
return map;
}
}
歡迎各位開發者朋友一起交流。筆者電話(微信):18629374628