需求:在工作中,经常会遇到,单位转换、数据计算这些繁琐的系列用算,很可能多个多个模块都遇到。 例如: 1、比如, 我们拿出来的 分, 实际上要是元 2、比如, 我们拿出来的 分, 实际上要是元 3、比如,我们拿到的数据需要 乘以100 返回给前端做 百分比展示 4、比如, 千分比转换 5、比如,拿出来的金额需要变成 万为单位 6、比如,需要保留2位小数
解决思路:首先,对于这些复杂的逻辑运算,我们可以去写一个工具类。 代码如下: MyYearSumReportDTO 这个类主要声明的一个dto,属性上的@JcBigDecConvert(name = UnitConvertType.B) 注解,是自己封装的,我们根据这个注解可以拿到,每一个数据要执行的一个运算规则
@Data
public class MyYearSumReportDTO implements Serializable {
private static final long serialVersionUID = 5285987517581372888L;
/**
* 支付总金额 例如:1100000---->110万
*/
@JcBigDecConvert(name = UnitConvertType.B)
private BigDecimal payTotalAmount;
/**
* jc金额百分比 例如:0.65------>65
*/
@JcBigDecConvert(name = UnitConvertType.PERCENTAGE)
private BigDecimal jcAmountPercentage;
/**
* jc计数千分比 例如:0.65------>650
*/
@JcBigDecConvert(name = UnitConvertType.PERMIL)
private BigDecimal jcCountPermillage;
/**
* 保留2位
*/
@JcBigDecConvert(name = UnitConvertType.R)
private BigDecimal length;
/**
* 保留2位
*/
@JcBigDecConvert(name = UnitConvertType.R)
private BigDecimal width;
}
封装的注解 @JcBigDecConvert
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface JcBigDecConvert {
UnitConvertType name();
}
枚举:
public enum UnitConvertType {
/**
* 精度
*/
R,
/**
* 万元
*/
B,
/**
* 百分
*/
PERCENTAGE,
/**
* 千分
*/
PERMIL
}
工具类 UnitConvertUtil
public static <T> void unitAnnotateConvert(List<T> list) throws IllegalAccessException {
for (T t : list) {
//获取到dto每个字段的属性
Field[] declaredFields = t.getClass().getDeclaredFields();
for (Field declaredField : declaredFields) {
if (declaredField.getName().equals("serialVersionuID")){
continue;
}
//获取字段上的注解
JcBigDecConvert myFieldAnn = declaredField.getAnnotation(JcBigDecConvert.class);
if(Objects.isNull(myFieldAnn)){
continue;
}
UnitConvertType unitConvertType = myFieldAnn.name();
declaredField.setAccessible(Boolean.TRUE);
Object o = declaredField.get(t);
if(!Objects.isNull(o)){
//执行对应的业务逻辑
if (unitConvertType.equals(UnitConvertType.PERCENTAGE)) {
BigDecimal bigDecimal = ((BigDecimal) o).multiply(new BigDecimal(100)).setScale(2, BigDecimal.ROUND_HALF_UP);
declaredField.set(t, bigDecimal);
}
if (unitConvertType.equals(UnitConvertType.PERMIL)) {
BigDecimal bigDecimal = ((BigDecimal) o).multiply(new BigDecimal(1000)).setScale(2, BigDecimal.ROUND_HALF_UP);
declaredField.set(t, bigDecimal);
}
if (unitConvertType.equals(UnitConvertType.B)) {
BigDecimal bigDecimal = ((BigDecimal) o).divide(new BigDecimal(10000)).setScale(2, BigDecimal.ROUND_HALF_UP);
declaredField.set(t, bigDecimal);
}
if (unitConvertType.equals(UnitConvertType.R)) {
BigDecimal bigDecimal = ((BigDecimal) o).setScale(2, BigDecimal.ROUND_HALF_UP);
declaredField.set(t, bigDecimal);
}
}
}
}
}
测试代码:
List<MyYearSumReportDTO> yearsList = getMyYearSumReportList();
log.info("转换之前:{}",yearsList);
unitAnnotateConvert(yearsList);
log.info("转换之后:{}",yearsList);