JAVA中利用反射如何将map转为实体类,拿去不谢
程序员文章站
2022-04-15 23:08:51
// map转化为bean//2020/07/15public static T autoBeanToMap(Class clazz ,Map map)throws Exception{ if (map == null){ return null; } //得到class T obj = clazz.newInstance(); Field[] fields = obj.getClass().getDeclaredField....
// map转化为bean
//2020/07/15
public static <T>T autoBeanToMap(Class<T> clazz ,Map map)throws Exception{
if (map == null){
return null;
}
//得到class
T obj = clazz.newInstance();
Field[] fields = obj.getClass().getDeclaredFields();
for (int i = 0; i < fields.length; i++) {
try {
//得到属性
Field field = fields[i];
//打开私有访问
field.setAccessible(true);
//获取属性
String name = field.getName();
if (map.containsKey(name)){
if (null!=map.get(name)){
field.set(obj,map.get(name).toString());
}else{
field.set(obj,"");
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
return obj;
}
本文地址:https://blog.csdn.net/weixin_44152010/article/details/107359962
上一篇: @NotNull 等验证注解使用
下一篇: 荐 Java程序是否跑的快全靠线程带!