两种方式:框架和反射
/**
* Created on 2019/11/13 18:55
* author:crs
* Description:map集合与对象之间的转换
*/
public class TestMapTransferObject {
@Autowired
private CacheClient cacheClient;
/**
* 把Object转化成map
*
* @param obj
*/
public Map<?, ?> objectToMap(Object obj) {
//方法1:通过jar包实现
if (obj == null) {
return null;
}
return new org.apache.commons.beanutils.BeanMap(obj);
}
/**
* 把map集合转化成对象
*
* @param map
*/
public Object mapToObject(Map<String, Object> map, Class<?> beanClass) throws Exception {
if (map == null) {
return null;
}
Object obj = beanClass.newInstance();
org.apache.commons.beanutils.BeanUtils.populate(obj, map);
return obj;
}
/**
* 如何把map集合存入到redis中
* Map集合对应的是Redis数据结构中哪种数据类型?HashMap
* 刷新cacheKey中的单个键值对,如何处理?
* 使用HashMap这种数据结构来存储用户的个人信息。因为用户的个人信息有多个。
*/
public void cacheMap() {
HashMap<String, String> map = new HashMap<>();
map.put("id", "11");
//空字符串
map.put("name", StringUtils.EMPTY);
String cacheKey = "token-doctor-11";
Set<Map.Entry<String, String>> entries = map.entrySet();
Iterator<Map.Entry<String, String>> iterator = entries.iterator();
while (iterator.hasNext()) {
Map.Entry<String, String> next = iterator.next();
String key = next.getKey();
String value = next.getValue();
cacheClient.hset(cacheKey, key, value);
}
}
//通过反射实现,获取对象上的属性名和属性值
public Object mapToObject1(Map<String, Object> map, Class<?> beanClass) throws Exception {
if (map == null) {
return null;
}
//遍历对象上所有的属性名称
Object obj = beanClass.newInstance();
Field[] fields = obj.getClass().getFields();
for (Field field : fields) {
int mod = field.getModifiers();
if (Modifier.isStatic(mod) || Modifier.isFinal(mod)) {
continue;
}
field.setAccessible(true);
//获取字段名称,字段对象,为字段名称设置值
String name = field.getName();
field.set(obj, map.get(name));
}
return obj;
}
//对象转化成map集合
public static Map<String, Object> objectToMap1(Object obj) throws Exception {
if (obj == null) {
return null;
}
Map<String, Object> map = new HashMap<>();
Field[] fields = obj.getClass().getFields();
for (Field field : fields) {
field.setAccessible(true);
String name = field.getName();
map.put(name,field.get(obj));
}
return map;
}
}
本文介绍Java中对象与Map集合相互转换的方法,包括使用BeanUtils库和反射技术,并展示了如何将Map集合存储到Redis中。适用于Java开发者理解和操作数据结构。
1983

被折叠的 条评论
为什么被折叠?



