From 3df525409b295ed24d3d2fbc953241df97cc3543 Mon Sep 17 00:00:00 2001 From: Looly Date: Mon, 9 May 2022 11:41:36 +0800 Subject: [PATCH] fix bug --- CHANGELOG.md | 1 + .../main/java/cn/hutool/core/bean/BeanUtil.java | 4 +++- .../java/cn/hutool/core/bean/BeanUtilTest.java | 17 +++++++++++++++++ 3 files changed, 21 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index bebec1343..3180b3fa4 100755 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,7 @@ * 【core 】 BooleanUtil增加toBooleanObject方法(issue#I56AG3@Gitee) ### 🐞Bug修复 * 【core 】 MapUtil.map对null友好,且修复了测试用例中分组问题(pr#614@Gitee) +* 【core 】 修复BeanUtil.beanToMap中properties为null的空指针问题(issue#2303@Github) ------------------------------------------------------------------------------------------------------------- diff --git a/hutool-core/src/main/java/cn/hutool/core/bean/BeanUtil.java b/hutool-core/src/main/java/cn/hutool/core/bean/BeanUtil.java index 5b8e517c3..84dee2e01 100755 --- a/hutool-core/src/main/java/cn/hutool/core/bean/BeanUtil.java +++ b/hutool-core/src/main/java/cn/hutool/core/bean/BeanUtil.java @@ -616,14 +616,16 @@ public class BeanUtil { * @since 5.8.0 */ public static Map beanToMap(Object bean, String... properties) { + int mapSize = 16; Editor keyEditor = null; if(ArrayUtil.isNotEmpty(properties)){ + mapSize = properties.length; final Set 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); } /** diff --git a/hutool-core/src/test/java/cn/hutool/core/bean/BeanUtilTest.java b/hutool-core/src/test/java/cn/hutool/core/bean/BeanUtilTest.java index 89de82f85..60f602fe0 100755 --- a/hutool-core/src/test/java/cn/hutool/core/bean/BeanUtilTest.java +++ b/hutool-core/src/test/java/cn/hutool/core/bean/BeanUtilTest.java @@ -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 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();