Map与Object互转
以前写接口时找到的方法,担心以后用到,记录下来。
/**
* 用于将object对象与map对象转换
* @author WANGJIE
*/
public class Transformation {
public static Object mapToObject(Map<String, Object> map, Class<?> beanClass) throws Exception {
if (map == null)
return null;
Object obj = beanClass.newInstance();
BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
for (PropertyDescriptor property : propertyDescriptors) {
Method setter = property.getWriteMethod();
if (setter != null) {
setter.invoke(obj, map.get(property.getName()));
}
}
return obj;
}
public static List<Object> mapListToObjectList(
List<Map<String, Object>> mapList, Class<?> beanClass)
throws Exception {
if (mapList == null)
return null;
List<Object> objList = new ArrayList<Object>();
for (Map<String, Object> map : mapList) {
Object obj = beanClass.newInstance();
BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
PropertyDescriptor[] propertyDescriptors = beanInfo
.getPropertyDescriptors();
for (PropertyDescriptor property : propertyDescriptors) {
Method setter = property.getWriteMethod();
if (setter != null) {
setter.invoke(obj, map.get(property.getName()));
}
}
objList.add(obj);
}
return objList;
}
public static Map<String, Object> objectToMap(Object obj) throws Exception {
if(obj == null)
return null;
Map<String, Object> map = new HashMap<String, Object>();
BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
for (PropertyDescriptor property : propertyDescriptors) {
String key = property.getName();
if (key.compareToIgnoreCase("class") == 0) {
continue;
}
Method getter = property.getReadMethod();
Object value = getter!=null ? getter.invoke(obj) : null;
map.put(key, value);
}
return map;
}
//String类型转date
public static Date StringToDate(String str,String format) throws ParseException{
SimpleDateFormat sim=new SimpleDateFormat(format);
Date d =sim.parse(str);
return d;
}
//String类型转Big
public static BigDecimal StringToBigDecimal(String str){
BigDecimal bd=new BigDecimal(str);
return bd;
}
}
实体类:
public class Users {
private String name;
private String age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
}
测试类:
public class test {
public static void main(String[] args) {
Map<String,Object> map = new HashMap<String,Object>();
map.put("name", "www.ixiaocao.cn");
map.put("age", "21");
Transformation t = new Transformation();
try {
Users u = (Users) t.mapToObject(map, Users.class);
System.out.println(u.getName());
System.out.println(u.getAge());
} catch (Exception e) {
e.printStackTrace();
}
}
}