工具类
非常棒的一个工具类
import org.springframework.cglib.beans.BeanMap;
import java.util.HashMap;
import java.util.Map;
/**
* Map集合与Bean对象转换 工具类
*/
public class BeanMapUtils {
/**
* 将对象属性转化为map结合
*/
public static <T> Map<String, Object> beanToMap(T bean) {
Map<String, Object> map = new HashMap<>(16);
if (bean != null) {
BeanMap beanMap = BeanMap.create(bean);
for (Object key : beanMap.keySet()) {
map.put(key + "", beanMap.get(key));
}
}
return map;
}
/**
* 将map集合中的数据转化为指定对象的同名属性中
*/
public static <T> T mapToBean(Map<String, Object> map, Class<T> clazz) throws Exception {
T bean = clazz.newInstance();
BeanMap beanMap = BeanMap.create(bean);
beanMap.putAll(map);
return bean;
}
}
测试案例
Map转Bean对象
/**
* Map转换Bean对象测试类
*
* @author MoCha
* @date 2019/6/9
*/
@Slf4j
@SpringBootTest
@RunWith(SpringRunner.class)
public class MapToBeanTest {
/**
* 测试Map转换Bean对象
*/
@Test
public void testMapToBean() {
Map<String, Object> map = new HashMap<>(16);
map.put("name", "MoCha");
map.put("password", "ijfaoidf");
map.put("age", 12);
User user = null;
try {
user = BeanMapUtils.mapToBean(map, User.class);
} catch (Exception e) {
log.error("异常信息 => {}", e.getMessage());
}
System.out.println("user = " + user);
}
}
user = User(name=MoCha, password=ijfaoidf, phone=null)
Bean对象转Map
/**
* Bean对象转换Map测试类
*
* @author MoCha
* @date 2019/6/9
*/
@Slf4j
@SpringBootTest
@RunWith(SpringRunner.class)
public class BeanToMapTest {
/**
* 测试Bean对象转换Map
*/
@Test
public void testBeanToMap() throws Exception {
User user = new User("MoCha", "", "10086");
Map<String, Object> map = BeanMapUtils.beanToMap(user);
System.out.println("map = " + map);
for (Map.Entry<String, Object> entry : map.entrySet()) {
System.out.println("key => " + entry.getKey() + ", value => " + entry.getValue());
}
}
}
map = {password=, phone=10086, name=MoCha}
key => password, value =>
key => phone, value => 10086
key => name, value => MoCha