直接上代码
/**
* @describe 例:map中有key为"id",value为"001"的数据,类对象为User,User中有Spring id;属性,
* 返回值:返回User对象,你将获得一个id属性为"001"的User对象
*/
public static <T> T mapToPOJO(Map map, Class clazz) throws Exception {
//通过class对象拿到所有的字段(包括私有)
Field[] declaredFields = clazz.getDeclaredFields();
//通过class对象拿到实例对象,虽然此时它是Object类型
Object newEntity = clazz.newInstance();
//循环Field[]拿到每个属性对象
for (Field field: declaredFields) {
//打开属性对象的赋值权限
field.setAccessible(true);
if (map.get(field.getName()) != null){
//然后通过map.get(field.getName())取到map里面的值field.set()进实例对象
field.set(newEntity,map.get(field.getName()));
}
}
//我们把Object转成泛型返回
return (T) newEntity;
}
这是优化后的代码
/**
* @author LiXin
* @date 2021-04-02 15:22
* @param map
* @param clazz
* @return T
* @describe 使用反射机制,用类的class对象获得类对象,把map中的值赋给类对象的对应属性
* 例:map中有key为"id",value为"001"的数据,类对象为User,User中有Spring id;属性,
* 返回值:返回User对象,你将获得一个id属性为"001"的User对象
*/
public static <T> T mapToPOJO(Map map, Class clazz) {
Field[] declaredFields = clazz.getDeclaredFields();
Object newEntity = null;
try {
newEntity = clazz.newInstance();
} catch (Exception e) {
log.error("获取对象失败",e.fillInStackTrace());
}
setFieldPOJO(map, declaredFields, newEntity);
return (T) newEntity;
}
/**
* @author LiXin
* @date 2021-04-02 16:10
* @param map
* @param declaredFields
* @param newEntity
* @describe 业务代码分离,这个方法是核心的处理部分,你如果能提供Field[]等参数,就可以直接调用此方法
*/
private static void setFieldPOJO(Map map, Field[] declaredFields, Object newEntity) {
for (Field field: declaredFields) {
field.setAccessible(true);
try {
if (map.get(field.getName()) != null){
field.set(newEntity,map.get(field.getName()));
}
} catch (IllegalAccessException e) {
log.error("属性赋值失败",e.fillInStackTrace());
}
}
}