fix boolean convert

This commit is contained in:
Looly 2020-08-16 09:14:56 +08:00
parent 279f056dc0
commit f72634c3a9
3 changed files with 33 additions and 2 deletions

View File

@ -20,6 +20,7 @@
* 【all 】 添加英文READMEpr#153@Gitee
* 【extra 】 SpringUtil增加getBean(TypeReference)pr#1009@Github
* 【core 】 Assert增加方法支持自定义异常处理pr#154@Gitee
* 【core 】 BooleanConverter增加数字转换规则issue#I1R2AB@Gitee
### Bug修复#
* 【core 】 修复原始类型转换时,转换失败没有抛出异常的问题

View File

@ -5,14 +5,26 @@ import cn.hutool.core.util.BooleanUtil;
/**
* 波尔转换器
* @author Looly
*
* <p>
* 对象转为boolean规则如下
* </p>
* <pre>
* 1数字0为false其它数字为true
* 2转换为字符串形如"true", "yes", "y", "t", "ok", "1", "on", "", "", "", "", ""为true其它字符串为false.
* </pre>
*
* @author Looly
*/
public class BooleanConverter extends AbstractConverter<Boolean>{
public class BooleanConverter extends AbstractConverter<Boolean> {
private static final long serialVersionUID = 1L;
@Override
protected Boolean convertInternal(Object value) {
if (value instanceof Number) {
// 0为false其它数字为true
return 0 != ((Number) value).doubleValue();
}
//Object不可能出现Primitive类型故忽略
return BooleanUtil.toBoolean(convertToStr(value));
}

View File

@ -0,0 +1,18 @@
package cn.hutool.core.convert;
import org.junit.Assert;
import org.junit.Test;
public class ConvertToBooleanTest {
@Test
public void intToBooleanTest(){
int a = 100;
final Boolean aBoolean = Convert.toBool(a);
Assert.assertTrue(aBoolean);
int b = 0;
final Boolean bBoolean = Convert.toBool(b);
Assert.assertFalse(bBoolean);
}
}