ICU-6037 Tightened currency code check in Currency#getInstance(String). Now it only accepts 3-letter alpha code.

X-SVN-Rev: 24136
This commit is contained in:
Yoshito Umaoka 2008-06-10 03:52:36 +00:00
parent c9e080cf8a
commit 15147e41b0
2 changed files with 81 additions and 43 deletions

View File

@ -47,6 +47,22 @@ public class CurrencyTest extends TestFmwk {
errln("FAIL: USD != USD");
}
try {
Currency nullCurrency = Currency.getInstance((String)null);
errln("FAIL: Expected getInstance(null) to throw "
+ "a NullPointerException, but returned " + nullCurrency);
} catch (NullPointerException npe) {
logln("PASS: getInstance(null) threw a NullPointerException");
}
try {
Currency bogusCurrency = Currency.getInstance("BOGUS");
errln("FAIL: Expected getInstance(\"BOGUS\") to throw "
+ "an IllegalArgumentException, but returned " + bogusCurrency);
} catch (IllegalArgumentException iae) {
logln("PASS: getInstance(\"BOGUS\") threw an IllegalArgumentException");
}
Locale[] avail = Currency.getAvailableLocales();
if(avail==null){
errln("FAIL: getAvailableLocales returned null");

View File

@ -266,10 +266,32 @@ public class Currency extends MeasureUnit implements Serializable {
* Returns a currency object given an ISO 4217 3-letter code.
* @param theISOCode the iso code
* @return the currency for this iso code
* @throws NullPoninterException if <code>theISOCode</code> is null.
* @throws IllegalArgumentException if <code>theISOCode</code> is not a
* 3-letter alpha code.
* @stable ICU 2.2
*/
public static Currency getInstance(String theISOCode) {
return new Currency(theISOCode);
if (theISOCode == null) {
throw new NullPointerException("The input currency code is null.");
}
boolean is3alpha = true;
if (theISOCode.length() != 3) {
is3alpha = false;
} else {
for (int i = 0; i < 3; i++) {
char ch = theISOCode.charAt(i);
if (ch < 'A' || (ch > 'Z' && ch < 'a') || ch > 'z') {
is3alpha = false;
break;
}
}
}
if (!is3alpha) {
throw new IllegalArgumentException(
"The input currency code is not 3-letter alphabetic code.");
}
return new Currency(theISOCode.toUpperCase(Locale.US));
}
/**