/**
* Map转成实体对象
*
* @param map 含实体对象属性
* @param clazz 实体对象类型
* @return
*/
public static Object map2Object(Map<String, Object> map, Class<?> clazz) {
if (map == null) {
return null;
}
Object obj = null;
try {
obj = clazz.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()));
}
} catch (Exception e) {
e.printStackTrace();
}
return obj;
}
//方法测试
public static void main(String[] args) {
Map<String, Object> o = new Hash<>();
o.put("name","hello");
o.put("age",18);
Student stu = (Student) map2Object(o, Student.class);
}
java实现Map集合key-value转化为对应的Object实体对象
最新推荐文章于 2024-06-22 11:03:50 发布