将java对象转为map
工具类
package top.jiqfu.commom.utils;
import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.aliyun.openservices.shade.org.apache.commons.lang3.reflect.FieldUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
/**
* 转换工具类
*
* @author: [email protected] 2020-1-2 19:32:28
*/
@Component
public class ConvertUtil {
private static final Logger logger = LoggerFactory.getLogger(ConvertUtil.class);
/**
* 将JavaBean对象封装到Map集合当中
*
* @param bean 对象
* @return 转换结果
*/
public static<T> Map<String, Object> toMap(T bean) throws IntrospectionException, InvocationTargetException, IllegalAccessException, NoSuchFieldException {
//创建Map集合对象
Map<String, Object> map = new HashMap<String, Object>();
Class<?> aClass = bean.getClass();
//获取对象字节码信息,不要Object的属性
BeanInfo beanInfo = Introspector.getBeanInfo(aClass, Object.class);
//获取bean对象中的所有属性
PropertyDescriptor[] list = beanInfo.getPropertyDescriptors();
for (PropertyDescriptor pd : list) {
//获取属性名
String key = pd.getName();
Field field = FieldUtils.getField(aClass, key, true);
TargetField targetField = ObjectUtils.isEmpty(field) ? null : field.getAnnotation(TargetField.class);
if (targetField != null && !"".equals(targetField.value())) {
key = targetField.value();
}
//调用getter()方法,获取内容
Object value = pd.getReadMethod().invoke(bean);
//增加到map集合当中
if (!ObjectUtils.isEmpty(value)) {
map.put(key, value);
}
}
return map;
}
/**
* 将list转为List Map
*
* @param list 集合
* @return 结果
*/
public static <T> List<Map<String, Object>> toList(List<T> list) {
List<Map<String, Object>> mapList = new ArrayList<>(list.size());
if (ObjectUtils.isEmpty(list)) {
return mapList;
}
for (T temp : list) {
try {
mapList.add(toMap(temp));
} catch (IntrospectionException e) {
e.printStackTrace();
logger.error("转换出错 {}", ExceptionUtils.getMessage(e));
} catch (IllegalAccessException e) {
e.printStackTrace();
logger.error("转换出错 {}", ExceptionUtils.getMessage(e));
} catch (InvocationTargetException e) {
e.printStackTrace();
logger.error("转换出错 {}", ExceptionUtils.getMessage(e));
} catch (NoSuchFieldException e) {
e.printStackTrace();
logger.error("转换出错 {}", ExceptionUtils.getMessage(e));
}
}
return mapList;
}
}
注解
package top.jiqfu.commom.utils;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD})
public @interface TargetField {
String value() default "";
}