//将map通过反射转化为实体 private Object MapToModel(Map<String,Object> map,Object o) throws Exception{ if (!map.isEmpty()) { for (String k : map.keySet()) { Object v =null; if (!k.isEmpty()) { v = map.get(k); } Field[] fields = null; fields = o.getClass().getDeclaredFields(); String clzName = o.getClass().getSimpleName(); for (Field field : fields) { int mod = field.getModifiers(); if (field.getName().toUpperCase().equals(k.toUpperCase())) { field.setAccessible(true); //region--进行类型判断 String type=field.getType().toString(); if (type.endsWith("String")){ if (v!=null){ v=v.toString(); }else { v=""; } } if (type.endsWith("Date")){ v=new Date(v.toString()); } if (type.endsWith("Boolean")){ v=Boolean.getBoolean(v.toString()); } if (type.endsWith("int")){ v=new Integer(v.toString()); } if (type.endsWith("Long")){ v=new Long(v.toString()); } //endregion field.set(o, v); } } } } return o; }
将map通过反射转化为实体
最新推荐文章于 2024-04-30 11:18:47 发布
本文介绍了一种使用Java反射机制将Map数据结构转换为Java实体对象的方法。该方法通过遍历Map的键值对,并根据实体类字段类型进行类型转换后设置到实体中。支持的类型包括String、Date、Boolean、int及Long等。
928

被折叠的 条评论
为什么被折叠?



