import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
public class EntityUtils {
/**
*
* @description: 实体类转Map
* @param object
* @return
*/
public static Map<String, Object> entityToMap(Object object) {
Map<String, Object> map = new HashMap<>();
for (Field field : object.getClass().getDeclaredFields()) {
try {
boolean flag = field.isAccessible();
field.setAccessible(true);
Object o = field.get(object);
map.put(field.getName(), o);
field.setAccessible(flag);
} catch (Exception e) {
e.printStackTrace();
}
}
return map;
}
/**
*
* @description: Map转实体类
* @param <T>
* @param map 需要初始化的数据,key字段必须与实体类的成员名字一样,否则赋值为空
* @param entity 需要转化成的实体类
* @return
*/
public static <T> T mapToEntity(Map<String, Object> map, Class<T> entity) {
T t = null;
try {
t = entity.newInstance();
for (Field field : entity.getDeclaredFields()) {
if (map.containsKey(field.getName())) {
boolean flag = field.isAccessible();
field.setAccessible(true);
Object object = map.get(field.getName());
if (object != null && field.getType().isAssignableFrom(object.getClass())) {
field.set(t, object);
}
field.setAccessible(flag);
}
}
return t;
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
return t;
}
public <T> T convertMapToBean(Class<T> clazz, Map<String,Object> map) {
T obj = null;
try {
BeanInfo beanInfo = Introspector.getBeanInfo(clazz);
obj = clazz.newInstance(); // 创建 JavaBean 对象
// 给 JavaBean 对象的属性赋值
PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
for (int i = 0; i < propertyDescriptors.length; i++) {
PropertyDescriptor descriptor = propertyDescriptors[i];
String propertyName = descriptor.getName();
if (map.containsKey(propertyName)) {
// 下面一句可以 try 起来,这样当一个属性赋值失败的时候就不会影响其他属性赋值。
Object value = map.get(propertyName);
if ("".equals(value)) {
value = null;
}
Object[] args = new Object[1];
args[0] = value;
descriptor.getWriteMethod().invoke(obj, args);
}
}
} catch (IllegalAccessException e) {
logger.error("convertMapToBean 实例化JavaBean失败 Error{}" ,e);
} catch (IntrospectionException e) {
logger.error("convertMapToBean 分析类属性失败 Error{}" ,e);
} catch (IllegalArgumentException e) {
logger.error("convertMapToBean 映射错误 Error{}" ,e);
} catch (InstantiationException e) {
logger.error("convertMapToBean 实例化 JavaBean 失败 Error{}" ,e);
}catch (InvocationTargetException e){
logger.error("convertMapToBean字段映射失败 Error{}" ,e);
}catch (Exception e){
logger.error("convertMapToBean Error{}" ,e);
}
return (T) obj;
}
}
java实体类map之间互相转换
最新推荐文章于 2024-07-19 22:00:34 发布