java实现map转换为bean对象
之前查看了apache beanutils 没有发现map转bean的方法,所以就自己实现了,这里记录一下,不过方法还存在很多为题,并未经过大量测试。
import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.*;
public class BeanUtils {
static Logger logger = LoggerFactory.getLogger(BeanUtils.class);
/**
* map转成bean
* 该方法调用需要保证map中的value与bean的属性是相同的类型,否则将转换失败
* @param <T>
* @param map
* @param t
* @return
*/
public static <T> T map2Bean(Map<String, Object> map, Class<T> t){
T o = null;
try {
o = t.newInstance();
BeanInfo beanInfo = Introspector.getBeanInfo(t);
PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
Set<Map.Entry<String, Object>> entrySet = map.entrySet();
for(Map.Entry<String, Object> entry : entrySet){
//遍历map中的key值
for(int i=0; i<propertyDescriptors.length; i++){
PropertyDescriptor pd = propertyDescriptors[i];
String propertyName = pd.getName();
//key值和bean的属性名
if(entry.getKey().equalsIgnoreCase(propertyName)) {
//进行基本类型的转换
if(null == entry.getValue()){
continue;
}
Method writeMethod = pd.getWriteMethod();
if(null != writeMethod) {
writeMethod.invoke(o, entry.getValue());
}
}
}
}
} catch (InstantiationException e) {
logger.error("map2Bean exception; e:", e);
} catch (IllegalAccessException e) {
logger.error("map2Bean exception; e:", e);
} catch (IntrospectionException e) {
logger.error("map2Bean exception; e:", e);
} catch (InvocationTargetException e) {
logger.error("map2Bean exception; e:", e);
}
return o;
}
/**
*
*
* @param list
* @param classType
* @param <T>
* @return
*/
public static <T> List<T> map2Bean(List<Map<String, Object>> list, Class<T> classType){
List<T> retList = new ArrayList<T>();
for(Map map : list) {
T t = (T)map2Bean(map, classType);
retList.add(t);
}
return retList;
}
}