我有一个 ISO 4217 数字货币代码:840
我想获取货币名称:USD
我正在尝试这样做:
Currency curr1 = Currency.getInstance("840");
但我不断得到
java.lang.IllegalArgumentException
怎么修?有任何想法吗?
java.util.Currency.getInstance
仅支持 ISO 4217 货币代码,不支持货币数字。但是,您可以使用该方法检索所有货币getAvailableCurrencies
,然后通过比较该getNumericCode
方法的结果来搜索代码为 840 的货币。
像这样:
public static Currency getCurrencyInstance(int numericCode) {
Set<Currency> currencies = Currency.getAvailableCurrencies();
for (Currency currency : currencies) {
if (currency.getNumericCode() == numericCode) {
return currency;
}
}
throw new IllegalArgumentException("Currency with numeric code " + numericCode + " not found");
}
使用 Java 8:
Optional<Currency> currency = Currency.getAvailableCurrencies().stream().filter(c -> c.getNumericCode() == 840).findAny();
一个更好的方法:
public class CurrencyHelper {
private static Map<Integer, Currency> currencies = new HashMap<>();
static {
Set<Currency> set = Currency.getAvailableCurrencies();
for (Currency currency : set) {
currencies.put(currency.getNumericCode(), currency);
}
}
public static Currency getInstance(Integer code) {
return currencies.get(code);
}
}
通过一些工作,缓存可以变得更高效。请查看 Currency 类的源代码以获取更多信息。
您必须提供像“USD”这样的代码,然后它将返回 Currency 对象。如果您使用的是 JDK 7,那么您可以使用以下代码。JDK 7 有一个方法 getAvailableCurrencies()
public static Currency getCurrencyByCode(int code) {
for(Currency currency : Currency.getAvailableCurrencies()) {
if(currency.getNumericCode() == code) {
return currency;
}
}
throw new IllegalArgumentException("Unkown currency code: " + code);
}