java BigDecimal包装器:静态字段为零
我的自定义Money
类是BigDecimal
和org.joda.money.Money
类的包装器
与BigDecimal
一样,我需要在我的应用程序中使用Money.ZERO
(通常在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
共 (0) 个答案