9

我有一个 ISO 4217 数字货币代码:840

我想获取货币名称:USD

我正在尝试这样做:

 Currency curr1 = Currency.getInstance("840");

但我不断得到

java.lang.IllegalArgumentException

怎么修?有任何想法吗?

4

4 回答 4

12

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");
}
于 2014-11-04T12:15:04.647 回答
5

使用 Java 8:

Optional<Currency> currency = Currency.getAvailableCurrencies().stream().filter(c -> c.getNumericCode() == 840).findAny();
于 2019-01-08T19:23:45.950 回答
2

一个更好的方法:

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 类的源代码以获取更多信息。

于 2018-11-25T02:24:51.217 回答
0

您必须提供像“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);
}
于 2014-11-04T12:17:44.690 回答