This commit is contained in:
Looly
2022-05-09 11:41:36 +08:00
parent cf9d2f62c1
commit 3df525409b
3 changed files with 21 additions and 1 deletions

View File

@@ -616,14 +616,16 @@ public class BeanUtil {
* @since 5.8.0
*/
public static Map<String, Object> beanToMap(Object bean, String... properties) {
int mapSize = 16;
Editor<String> keyEditor = null;
if(ArrayUtil.isNotEmpty(properties)){
mapSize = properties.length;
final Set<String> propertiesSet = CollUtil.set(false, properties);
keyEditor = property -> propertiesSet.contains(property) ? property : null;
}
// 指明了要复制的属性 所以不忽略null值
return beanToMap(bean, new LinkedHashMap<>(properties.length, 1), false, keyEditor);
return beanToMap(bean, new LinkedHashMap<>(mapSize, 1), false, keyEditor);
}
/**

View File

@@ -191,6 +191,23 @@ public class BeanUtilTest {
Assert.assertFalse(map.containsKey("SUBNAME"));
}
@Test
public void beanToMapNullPropertiesTest() {
SubPerson person = new SubPerson();
person.setAge(14);
person.setOpenid("11213232");
person.setName("测试A11");
person.setSubName("sub名字");
Map<String, Object> map = BeanUtil.beanToMap(person, null);
Assert.assertEquals("测试A11", map.get("name"));
Assert.assertEquals(14, map.get("age"));
Assert.assertEquals("11213232", map.get("openid"));
// static属性应被忽略
Assert.assertFalse(map.containsKey("SUBNAME"));
}
@Test
public void beanToMapTest2() {
SubPerson person = new SubPerson();