有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java BigDecimal包装器:静态字段为零

我的自定义Money类是BigDecimalorg.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) 个答案