我的自定义类是和类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永远保持不变的领域。
扬帆大鱼
相关分类