我有一个 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”之类的代码,然后它将返回货币对象。如果您使用的是 JDK 7,则可以使用以下代码。 JDK 7 有一个方法 getAvailableCurrency()
public static Currency getCurrencyByCode(int code) {
for(Currency currency : Currency.getAvailableCurrencies()) {
if(currency.getNumericCode() == code) {
return currency;
}
}
throw new IllegalArgumentException("Unkown currency code: " + code);
}
我也查看了其他评论,但最有效的工作版本如下:
public final class CurrencyFinder {
private CurrencyFinder() {
}
private static final Set<Currency> AVAILABLE_CURRENCIES = Currency.getAvailableCurrencies();
public static Optional<Currency> find(String currencyCode) {
return AVAILABLE_CURRENCIES.stream()
.filter(currency -> Objects.equals(currency.getCurrencyCode(), currencyCode))
.findFirst();
}
public static Optional<Currency> find(Integer numericCode) {
return AVAILABLE_CURRENCIES.stream()
.filter(currency -> currency.getNumericCode() == numericCode)
.findFirst();
}
}
在进行这些转换时,我注意到一些
值是相同的,我认为这是需要注意的重要一点。特别是如果要开展一个项目,我建议使用numericCode
值而不是currencyCode
值。numericCode