把对象中所有属性中类型为BigDecimal的统一赋值0
当我们需要插入一个对象到数据库中,且该对象有很多属性都是BigDecimal时,我们想要把其中空值的属性字段统一赋值为0,方便后续对该类型字段进行计算等操作。
自定义一个工具方法:
运用java类的反射机制,便利类的所有字段,如果字段的类型属于BigDecimal,则获取对象字段值,如果值为空,默认给0.当然下面方法有一个flag参数用来设置是否给对象所有 BigDecimal 类型的 全部 默认为0处 理。
public class powerUtils {
/**
* @Author: power
* @Description: 对传入的值 含有BigDecimal 类型的 全部 默认为0处理!
* @param: object flag true 则空值设置为0 false 则所有 BigDecimal 类型的 全部 默认为0处 理!
*/
public static void initBigDecimalToZero(Object object,boolean flag){
Class<?> aClass = object.getClass();
Field[] fields = aClass.getDeclaredFields();
for (Field field : fields) {
Class<?> type = field.getType();
if(BigDecimal.class.equals(type)){
try {
if(flag){
BigDecimal result = (BigDecimal) BeanUtil.getFieldValue(object,field.getName());
if (result == null){
//cn.hutool.core.bean.BeanUtil ,给属性赋值
BeanUtil.setFieldValue(object,field.getName(),BigDecimal.ZERO);
}
}else{
BeanUtil.setFieldValue(object,field.getName(),BigDecimal.ZERO);
}
} catch (Exception e) {
log.error(e.getMessage());
}
}
}
}
}
具体的类如下,所有BigDecimal 类型的参数都会被执行。
@Data
public class studentInfo implements Serializable {
private static final long serialVersionUID=1L;
@ApiModelProperty(value = "主键id")
private Long id;
@ApiModelProperty(value = "报到日期")
private String reportDate;
@ApiModelProperty(value = "减免学费")
private BigDecimal deratebizBal;
@ApiModelProperty(value = "生活费")
private BigDecimal liveBal;
@ApiModelProperty(value = "非批金额")
private BigDecimal nonBatchBal;
}
具体使用场景:
powerUtils.initBigDecimalToZero(studentInfo,false);