cn.hutool.core.convert.impl.NumberConverter Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of hutool-all Show documentation
Show all versions of hutool-all Show documentation
Hutool是一个小而全的Java工具类库,通过静态方法封装,降低相关API的学习成本,提高工作效率,使Java拥有函数式语言般的优雅,让Java语言也可以“甜甜的”。
package cn.hutool.core.convert.impl;
import cn.hutool.core.convert.AbstractConverter;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.ByteUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.time.temporal.TemporalAccessor;
import java.util.Calendar;
import java.util.Date;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.DoubleAdder;
import java.util.concurrent.atomic.LongAdder;
import java.util.function.Function;
/**
* 数字转换器
* 支持类型为:
*
* - {@code java.lang.Byte}
* - {@code java.lang.Short}
* - {@code java.lang.Integer}
* - {@code java.util.concurrent.atomic.AtomicInteger}
* - {@code java.lang.Long}
* - {@code java.util.concurrent.atomic.AtomicLong}
* - {@code java.lang.Float}
* - {@code java.lang.Double}
* - {@code java.math.BigDecimal}
* - {@code java.math.BigInteger}
*
*
* @author Looly
*/
public class NumberConverter extends AbstractConverter {
private static final long serialVersionUID = 1L;
private final Class extends Number> targetType;
/**
* 构造
*/
public NumberConverter() {
this.targetType = Number.class;
}
/**
* 构造
*
* @param clazz 需要转换的数字类型,默认 {@link Number}
*/
public NumberConverter(Class extends Number> clazz) {
this.targetType = (null == clazz) ? Number.class : clazz;
}
@Override
@SuppressWarnings("unchecked")
public Class getTargetType() {
return (Class) this.targetType;
}
@Override
protected Number convertInternal(Object value) {
return convert(value, this.targetType, this::convertToStr);
}
@Override
protected String convertToStr(Object value) {
final String result = StrUtil.trim(super.convertToStr(value));
if (null != result && result.length() > 1) {
final char c = Character.toUpperCase(result.charAt(result.length() - 1));
if (c == 'D' || c == 'L' || c == 'F') {
// 类型标识形式(例如123.6D)
return StrUtil.subPre(result, -1);
}
}
return result;
}
/**
* 转换对象为数字,支持的对象包括:
*
* - Number对象
* - Boolean
* - byte[]
* - String
*
*
*
* @param value 对象值
* @param targetType 目标的数字类型
* @param toStrFunc 转换为字符串的函数
* @return 转换后的数字
* @since 5.5.0
*/
protected static Number convert(Object value, Class extends Number> targetType, Function
© 2015 - 2024 Weber Informatics LLC | Privacy Policy