我的自定義類是和類Money的一種包裝。BigDecimalorg.joda.money.Money與之前一樣BigDecimal,我需要Money.ZERO在我的應用程序中使用 a (通常在reduce()操作中)。我發(fā)現(xiàn)我Money.ZERO在應用程序執(zhí)行期間的更改(它的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數(shù)量BigDecimal.ZERO永遠保持不變的領域。
1 回答

揚帆大魚
TA貢獻1799條經(jīng)驗 獲得超9個贊
您正在修改內(nèi)部狀態(tài)。
看看你的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
提交
取消