我的自定义类是和类Money的一种包装。BigDecimalorg.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永远保持不变的领域。
1 回答
扬帆大鱼
TA贡献1799条经验 获得超9个赞
您正在修改内部状态。
看看你的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方法。
添加回答
举报
0/150
提交
取消