Confirm successful string conversion to enum in Java

I have a list of account types defined as enumerations in a web services implementation. However, when the consumer call web service passes a string that must be converted to an enumeration.

What is a good way to verify that a given string will be successfully converted to an enumeration?

I used the following approach, but this is probably an abuse of exceptions (according to Effective Java, paragraph 57).

AccountType accountType = null;
try{
    accountType = AccountType.valueOf(accountTypeString);
}catch(IllegalArgumentException e){
    // report error
}

if (accountType != null){
    // do stuff
}else{
    // exit
}
+5
source share
4 answers

You can list the enumeration values ​​and check if the name of each literal matches your string with something like

for (Test test : Test.values()) {
    if (str.equals(test.name())) {
        return true;
    }
}
return false;

Listing:

public enum Test {
    A,
    B,
}

null, , , , .

+2

EnumUtils Apache Commons.

(, ), Java (300ko).

, :

TypeEnum strTypeEnum = null;

// test if String str is compatible with the enum 
if( EnumUtils.isValidEnum(TypeEnum.class, str) ){
    strTypeEnum = TypeEnum.valueOf(str);
}
+2

IllegalArgumentException, .

0

Optional Guava.

AccountType.valueOf Optional<AccountType>. :

Optional<AccountType> accountType = AccountType.valueOf(accountTypeString));
if (accountType.isPresent()) {
  AccountType a = accountType.get();
  // do stuff
} else {
  // exit
}
0

All Articles