Money
IMO、最も簡単な解決策は、情報、お金の種類(つまり、通貨)とお金の価値の両方を保持する別のJavaクラスsayを作成することです。
public class Money {
private Currency currency;
private Double value;
public Currency getCurrency() { return currency; }
public void setCurrency(Currency currency) { this.currency = currency; }
public Double getValue() { return value; }
public void setValue(Double value) { this.value = value; }
public boolean isValid() {
if(getCurrency() == null || getValue() == null) {
return false;
}
// critical logic goes here
// sample code
if("JPY".equalsIgnoreCase(currency.getCurrencyCode())) {
int intValue = getValue().intValue();
double diff = getValue() - intValue;
if(diff > 0) {
return false;
}
}
/*double fractionValue = value - (value % (currency.getDefaultFractionDigits() * 10));
if(fractionValue > currency.getDefaultFractionDigits() * 10) {
return false;
}*/
return true;
}
}
この後、制約say@ValidMoney
とを作成しますMoneyValidator
。
public class MoneyValidator implements ConstraintValidator<ValidMoney, Money> {
@Override
public void initialize(ValidMoney constraintAnnotation) {
// TODO Auto-generated method stub
}
@Override
public boolean isValid(Money value, ConstraintValidatorContext context) {
return value.isValid();
}
}
例:-
public class Bid {
@ValidMoney
private Money bidAmount;
}