前言
实际开发中总是存在java与map想换转换的事情,而这种事公共方法可以写成一个工具类来处理。代码如下:
代码
MapUtils.java 工具类代码:
package com.kq.cloud.common.util;
import org.apache.commons.collections.map.LinkedMap;
import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.util.Map;
/**
* @author iceter
* @Date 2019/04/30
*/
public class MapUtils {
public static Object transMap(Class type, Map map) throws Exception {
Object obj = type.newInstance();//实例化类
BeanInfo info = Introspector.getBeanInfo(type);//获取类中属性
PropertyDescriptor[] propertyPermissions = info.getPropertyDescriptors();
for (PropertyDescriptor pro : propertyPermissions) {
String proName = pro.getName();
if(map.containsKey(proName)){
Object methodName = map.get(proName);
Object[] args = {methodName};
try {
pro.getWriteMethod().invoke(obj,args);
}catch (Exception e){
e.printStackTrace();
}
}
}
return obj;
}
public static void main(String[] args) throws Exception {
Map map = new LinkedMap();
map.put("age",11);
map.put("id","33");
map.put("sex","man");
map.put("name","fei");
map.put("addr","neyok");
User user = (User) MapUtils.transMap(User.class,map);
System.out.println(user);
}
}
实体类代码
user.java 实体类代码
package com.kq.cloud.common.util;
public class User {
private String id;
private String name;
private String sex;
private Integer age;
private String addr;
@Override
public String toString() {
return "User{" +
"id='" + id + '\'' +
", name='" + name + '\'' +
", sex='" + sex + '\'' +
", age=" + age +
", addr='" + addr + '\'' +
'}';
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getAddr() {
return addr;
}
public void setAddr(String addr) {
this.addr = addr;
}
}
目前只写了map转换为实体类,实体类转换为map就自己比着葫芦画瓢吧。
文中代码下载地址:https://download.csdn.net/download/u011561335/11153791