This commit is contained in:
Looly 2022-05-09 11:51:45 +08:00
parent fddaf71a8b
commit a727984f38
3 changed files with 44 additions and 1 deletions

View File

@ -573,14 +573,16 @@ public class BeanUtil {
* @since 5.8.0
*/
public static Map<String, Object> beanToMap(final Object bean, final String... properties) {
int mapSize = 16;
Editor<String> keyEditor = null;
if(ArrayUtil.isNotEmpty(properties)){
mapSize = properties.length;
final Set<String> propertiesSet = SetUtil.of(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

@ -16,6 +16,8 @@ public class BooleanUtil {
/** 表示为真的字符串 */
private static final Set<String> TRUE_SET = SetUtil.of("true", "yes", "y", "t", "ok", "1", "on", "", "", "", "", "");
/** 表示为假的字符串 */
private static final Set<String> FALSE_SET = SetUtil.of("false", "no", "n", "f", "0", "off", "", "", "", "", "×");
/**
* 取相反值
@ -86,6 +88,28 @@ public class BooleanUtil {
return false;
}
/**
* 转换字符串为boolean值<br>
* 如果为["true", "yes", "y", "t", "ok", "1", "on", "", "", "", "", ""]返回{@code true}<br>
* 如果为["false", "no", "n", "f", "0", "off", "", "", "", "", "×"]返回{@code false}<br>
* 其他情况返回{@code null}
*
* @param valueStr 字符串
* @return boolean值
* @since 5.8.1
*/
public static Boolean toBooleanObject(String valueStr) {
if (StrUtil.isNotBlank(valueStr)) {
valueStr = valueStr.trim().toLowerCase();
if(TRUE_SET.contains(valueStr)){
return true;
} else if(FALSE_SET.contains(valueStr)){
return false;
}
}
return null;
}
/**
* boolean值转为int
*

View File

@ -191,6 +191,23 @@ public class BeanUtilTest {
Assert.assertFalse(map.containsKey("SUBNAME"));
}
@Test
public void beanToMapNullPropertiesTest() {
final SubPerson person = new SubPerson();
person.setAge(14);
person.setOpenid("11213232");
person.setName("测试A11");
person.setSubName("sub名字");
final Map<String, Object> map = BeanUtil.beanToMap(person, (String[])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() {
final SubPerson person = new SubPerson();