package com.test;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import org.apache.commons.beanutils.BeanUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.pojo.User;
public class TestMapBeanConvert {
private static Logger LOGGER = LoggerFactory.getLogger(TestMapBeanConvert.class);
// 将map转为bean
public staticT mapToBean(Map<String, Object> map, Class clz) {
T bean = null;
try {
bean = clz.newInstance();
// 遍历map中的key,若bean中有这个属性(key),将key对应的value赋值给bean对应的属性
BeanUtils.populate(bean, map); // 将map转为bean
} catch (Exception e) {
LOGGER.info("ERROR ------> " + e.getMessage());
}
return bean;
}
// 将bean转为map
public staticMapbeanToMap(Object bean) {
Map<String, String> map = null;
try {
map = BeanUtils.describe(bean); // 将bean转为map
} catch (Exception e) {
LOGGER.info("ERROR ------> " + e.getMessage());
}
return map;
}
public static void main(String[] args) {
Map<String, Object> map = new HashMap<String, Object>();
map.put("name", "六月");
map.put("age",6);
System.err.println("-------------------- from map to bean --------------------");
User user = mapToBean(map, User.class);System.err.println(user.toString());
System.err.println("-------------------- from bean to map --------------------");
Map<String, String> toMap = beanToMap(user);
for(Entry<String, String> entry:toMap.entrySet()){
System.out.println("key=" +entry.getKey() +" and value="+entry.getValue());
}
}
}