map集合和javabean对象之间相互转换方法
亲测可用, 简单易读
1、使用反射
/**
* 使用reflect进行转换,map集合转javabean
*
* @param map
* @param beanClass
* @return
* @throws IllegalAccessException
* @throws InstantiationException
*/
public static Object mapToObject(Map<String, Object> map, Class<?> beanClass) throws IllegalAccessException, InstantiationException {
if (map == null){
return null;
}
Object obj = beanClass.newInstance();
Field[] fields = obj.getClass().getDeclaredFields();
for (Field field : fields) {
int mod = field.getModifiers();
if (Modifier.isStatic(mod) || Modifier.isFinal(mod)) {
continue;
}
field.setAccessible(true);
field.set(obj, map.get(field.getName()));
}
return obj;
}
/**
* 使用reflect进行转换,javabean对象转map集合
*
* @param obj
* @return map集合
* @throws IllegalAccessException java.lang.IllegalAccessException
* @throws InstantiationException java.lang.InstantiationException
*/
public static Map<String, Object> objectToMap(Object obj) throws Exception {
if (obj == null) {
return null;
}
Map<String, Object> map = new HashMap<String, Object>();
Field[] declaredFields = obj.getClass().getDeclaredFields();
for (Field field : declaredFields) {
field.setAccessible(true);
map.put(field.getName(), field.get(obj));
}
return map;
}
2、使用Introspector(推荐)
/**
* 使用Introspector,map集合成javabean
*
* @param map map
* @param beanClass bean的Class类
* @return bean对象
*/
public static <T> T mapToBean(Map<String, Object> map, Class<T> beanClass) {
if (MapUtils.isEmpty(map)) {
return null;
}
try {
T t = beanClass.newInstance();
BeanInfo beanInfo = Introspector.getBeanInfo(t.getClass());
PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
for (PropertyDescriptor property : propertyDescriptors) {
Method setter = property.getWriteMethod();
if (setter != null) {
setter.invoke(t, map.get(property.getName()));
}
}
return t;
} catch (Exception ex) {
log.error("########map集合转javabean出错######,错误信息,{}", ex.getMessage());
throw new RuntimeException();
}
}
/**
* 使用Introspector,对象转换为map集合
*
* @param beanObj javabean对象
* @return map集合
*/
public static Map<String, Object> beanToMap(Object beanObj) {
if (null == beanObj) {
return null;
}
Map<String, Object> map = new HashMap<>();
try {
BeanInfo beanInfo = Introspector.getBeanInfo(beanObj.getClass());
PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
for (PropertyDescriptor property : propertyDescriptors) {
String key = property.getName();
if (key.compareToIgnoreCase("class") == 0) {
continue;
}
Method getter = property.getReadMethod();
Object value = getter != null ? getter.invoke(beanObj) : null;
map.put(key, value);
}
return map;
} catch (Exception ex) {
log.error("########javabean集合转map出错######,错误信息,{}", ex.getMessage());
throw new RuntimeException();
}
}
原贴地址:https://blog.csdn.net/hanxue6898/article/details/81187104
还没有评论,来说两句吧...