java - BigDecimal 包装器:拥有零静态字段
问题描述
我的自定义Money
类是类的一种包装BigDecimal
器org.joda.money.Money
。
和以前一样BigDecimal
,我需要Money.ZERO
在我的应用程序周围使用 a (通常在reduce()
操作中)。
我发现我Money.ZERO
在应用程序执行期间所做的更改(也就是说,它的amount
值可能不是零)导致无效结果。
下面是我的自定义Money
类:
@Getter
@Embeddable
@NoArgsConstructor(access = AccessLevel.PRIVATE)
@AllArgsConstructor(access = AccessLevel.PRIVATE)
public class Money implements Serializable {
private static final long serialVersionUID = -4274180309004444639L;
public static final Money ZERO = new Money(BigDecimal.ZERO, CurrencyUnit.EUR);
private BigDecimal amount;
@Convert(converter = CurrencyUnitToStringConverter.class)
private CurrencyUnit currency;
public static Money of(BigDecimal amount, CurrencyUnit currency) {
return new Money(amount, currency);
}
public Money add(Money addition) {
checkCurrency(addition);
amount = amount.add(addition.getAmount());
return new Money(amount, currency);
}
public Money substract(Money reduction) {
checkCurrency(reduction);
amount = amount.subtract(reduction.getAmount());
return new Money(amount, currency);
}
private void checkCurrency(Money other) {
if (!Objects.equal(getCurrency(), other.getCurrency())) {
throw new IllegalArgumentException("Currency does not match when adding amounts!");
}
}
所以我的目标是拥有一个ZERO
数量BigDecimal.ZERO
永远保持不变的领域。
解决方案
您正在修改内部状态。
看看你的add
方法:
public Money add(Money addition) {
checkCurrency(addition);
amount = amount.add(addition.getAmount());
return new Money(amount, currency);
}
在这种方法中,您正在重新分配amount
,因此会更改当前Money
实例的值。
这是一个简单的修复:
public Money add(Money addition) {
checkCurrency(addition);
BigDecimal newAmount = amount.add(addition.getAmount());
return new Money(newAmount, currency);
}
这同样适用于你的substract
方法。
推荐阅读
- splunk - 如何在 splunk 中搜索:documentID = NM_APEXIT,{FFAAAA8-59EB-457F-A831-B532CACF20C1},{6080D6666-666-C00B-999C-3C42BBBBBB}
- python - 使用python将文件内容连接到一个文件中
- django - 如何使用 Django 和模板标签正确地从数据库中提取
- python-3.x - 如何使用 Python 3.x 转换具有特定程序的文件扩展名?
- python - 图例位置和比例值字体大小pygal python
- javascript - Angular:单击浏览器后退按钮将用户带回家
- java - 将 datainputstream 中的数据写入 Java 中的文件
- c# - 单击 asp:RadioButton 时如何调用方法?
- android - 使用默认拨号器应用程序取消拨出电话
- microsoft-graph-api - 创建 onenote 页面失败,出现 404