Christian
Christian

Reputation: 23

JavaMoney: set CurrencyStyle without a compile-time dependency on moneta

I'm trying to create a MonetaryAmountFormat that uses the currency unit symbol:

MonetaryAmountFormat format = MonetaryFormats.getAmountFormat(
  AmountFormatQueryBuilder.of(Locale.GERMANY)
                          .set(org.javamoney.moneta.format.CurrencyStyle.SYMBOL)
                          .set("pattern", "#,##0.##¤")
                          .build()
);

(Taken from How to format MonetaryAmount with currency symbol? and Customizing a MonetaryAmountFormat using the Moneta (JavaMoney) JSR354 implemenation).

The java/maven project has a dependency on moneta in runtime (not compile-time) scope. It seems that the class CurrencyStyle and its value SYMBOL are part of moneta, the java-money reference implementation, and not part of the java-money API. Thus, the code does not compile.

I created this ugly workaround:

String currencyStyle = "org.javamoney.moneta.format.CurrencyStyle";
final Enum<?> SYMBOL = Enum.valueOf((Class<? extends Enum>) Class.forName(currencyStyle), "SYMBOL");
MonetaryAmountFormat format = MonetaryFormats.getAmountFormat(
  AmountFormatQueryBuilder.of(Locale.GERMANY)
                          .set(currencyStyle, SYMBOL)
                          .set("pattern", "#,##0.##¤")
                          .build()
);

Is it possible to create a MonetaryAmountFormat that uses the currency unit symbol without this hack?

Upvotes: 1

Views: 508

Answers (1)

Christian
Christian

Reputation: 146

Maybe using DecimalFormat as alternative to MonetaryAmountFormat is an option.

Drawbacks:

  • Conversion between Number and MonetaryAmount must be done manually
  • Works only when you don't have changing currency units (unit is taken from the format, not from the MonetaryAmount object)

Example:

NumberFormat format = new DecimalFormat("#,##0.##¤", DecimalFormatSymbols.getInstance(Locale.GERMANY));

// format
MonetaryAmount source = ...;
String formattedAmount = format.format(source.getNumber());

// parse
Number numberAmount = format.parse(formattedAmount);
MonetaryAmount target = Monetary.getDefaultAmountFactory().setCurrency("EUR").setNumber(numberAmount).create()

Upvotes: 0

Related Questions