1.update Convert.toMap, If value is a map type, use its own type; otherwise, use HashMap

2.add Convert.toMap, Overload a method to specify the map type of conversion
This commit is contained in:
wenbei 2022-07-26 11:55:00 +08:00
parent 630ed4775f
commit de52d71031
2 changed files with 48 additions and 2 deletions

View File

@ -601,7 +601,7 @@ public class Convert {
}
/**
* 转换为Map
* 转换为Map若value原本就是Map则使用原始类型若不是
*
* @param <K> 键类型
* @param <V> 值类型
@ -613,7 +613,27 @@ public class Convert {
*/
@SuppressWarnings("unchecked")
public static <K, V> Map<K, V> toMap(Class<K> keyType, Class<V> valueType, Object value) {
return (Map<K, V>) new MapConverter(HashMap.class, keyType, valueType).convert(value, null);
if(value instanceof Map){
return toMap((Class<? extends Map>) value.getClass(), keyType, valueType,value);
}else{
return toMap(HashMap.class, keyType, valueType,value);
}
}
/**
* 转换为Map
*
* @param mapType 转后的具体Map类型
* @param <K> 键类型
* @param <V> 值类型
* @param keyType 键类型
* @param valueType 值类型
* @param value 被转换的值
* @return {@link Map}
*/
@SuppressWarnings("unchecked")
public static <K, V> Map<K, V> toMap(Class<? extends Map> mapType, Class<K> keyType, Class<V> valueType, Object value) {
return (Map<K, V>) new MapConverter(mapType, keyType, valueType).convert(value, null);
}
/**

View File

@ -2,6 +2,7 @@ package cn.hutool.core.convert;
import cn.hutool.core.bean.BeanUtilTest.SubPerson;
import cn.hutool.core.lang.TypeReference;
import cn.hutool.core.map.CaseInsensitiveMap;
import org.junit.Assert;
import org.junit.Test;
@ -67,7 +68,32 @@ public class ConvertToBeanTest {
Assert.assertEquals("3", map2.get("key3"));
Assert.assertEquals("4", map2.get("key4"));
}
@Test
public void mapToMapWithSelfTypeTest() {
CaseInsensitiveMap<String, Integer> caseInsensitiveMap = new CaseInsensitiveMap<>();
caseInsensitiveMap.put("jerry", 1);
caseInsensitiveMap.put("Jerry", 2);
caseInsensitiveMap.put("tom", 3);
Map<String, String> map = Convert.toMap(String.class, String.class, caseInsensitiveMap);
Assert.assertEquals("2", map.get("jerry"));
Assert.assertEquals("2", map.get("Jerry"));
Assert.assertEquals("3", map.get("tom"));
}
@Test
public void beanToSpecifyMapTest() {
SubPerson person = new SubPerson();
person.setAge(14);
person.setOpenid("11213232");
person.setName("测试A11");
person.setSubName("sub名字");
Map<String, String> map = Convert.toMap(LinkedHashMap.class, String.class, String.class, person);
Assert.assertEquals("测试A11", map.get("name"));
Assert.assertEquals("14", map.get("age"));
Assert.assertEquals("11213232", map.get("openid"));
}
@Test
public void mapToBeanTest() {
HashMap<String, Object> map = new HashMap<>();