Java map转Object例子
先定义一个DTO
public class RoleInfo {
private String roleName;
private String roleCode;
private Integer level;
private Date createTime;
private Boolean vaild;
public String getRoleName() {
return roleName;
}
public void setRoleName(String roleName) {
this.roleName = roleName;
}
public String getRoleCode() {
return roleCode;
}
public void setRoleCode(String roleCode) {
this.roleCode = roleCode;
}
public Integer getLevel() {
return level;
}
public void setLevel(Integer level) {
this.level = level;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public Boolean getVaild() {
return vaild;
}
public void setVaild(Boolean vaild) {
this.vaild = vaild;
}
@Override
public String toString(){
return "RoleInfo[roleName="+roleName +",roleCode="+roleCode+",level="+level+",createTime="+createTime+",vaild="+vaild+"]";
}
}
map to object 类型
public class MapToObject {
public static Object mapToObject(Map<String, Object> map, Class cls) throws Exception {
if (map == null || map.size() == 0) {
return cls.newInstance();
}
Object t = cls.newInstance();
Field[] fields = cls.getDeclaredFields();
Method[] methods = cls.getDeclaredMethods();
Map<String, Method> methodMap = new HashMap<>();
for (Method me : methods) {
methodMap.put(me.getName().toUpperCase(), me);
}
Set<String> keySet = map.keySet();
Set<String> methodSet = methodMap.keySet();
for (Field field : fields) {
String name = field.getName();
if (keySet.contains(name)) {
String attrName = "SET" + name.toUpperCase();
if (methodSet.contains(attrName)) {
if (field.getType().getTypeName().compareToIgnoreCase(map.get(name).getClass().getTypeName()) != 0) {
throw new Exception("设值方法参数类型不匹配,attr:" + name + ",type:" + field.getType().getTypeName() + ",参数类型:" + map.get(name).getClass().getTypeName());
}
Method m = methodMap.get(attrName);
m.invoke(t, map.get(name));
}
}
}
return t;
}
public static void main(String[] args) {
Map<String, Object> map = new HashMap<>();
map.put("roleName", "影像管理岗");
map.put("roleCode", "Role-2001");
map.put("level", 1);
map.put("createTime", new Date());
map.put("vaild", false);
try {
RoleInfo role = (RoleInfo) MapToObject.mapToObject(map, RoleInfo.class);
System.out.println(role.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
}