Reputation: 1828
I have a list of accounts types defined as enums in the web services implementation. However, when consumer call web service it passes a String that needs to be converted to enum.
What is a good way to validate that given String will be successfully converted to enum?
I was using the following approach, but this is probably an abuse of exceptions (according to Effective Java, item 57).
AccountType accountType = null;
try{
accountType = AccountType.valueOf(accountTypeString);
}catch(IllegalArgumentException e){
// report error
}
if (accountType != null){
// do stuff
}else{
// exit
}
Upvotes: 4
Views: 4482
Reputation: 5448
I personally used the EnumUtils from the Apache Commons library.
That library contains many useful util classes (e.g for Strings as well) and is a must have in any Java project and quite light (300ko).
Here is a sample code I use:
TypeEnum strTypeEnum = null;
// test if String str is compatible with the enum
if( EnumUtils.isValidEnum(TypeEnum.class, str) ){
strTypeEnum = TypeEnum.valueOf(str);
}
Upvotes: 2
Reputation: 92066
Use Optional
data type from Guava.
Have your method AccountType.valueOf
return value of type Optional<AccountType>
. Then the use-site code would become:
Optional<AccountType> accountType = AccountType.valueOf(accountTypeString));
if (accountType.isPresent()) {
AccountType a = accountType.get();
// do stuff
} else {
// exit
}
Upvotes: 0
Reputation: 4704
You could go over the enum values and check if the name of each literal is equal to your string something like
for (Test test : Test.values()) {
if (str.equals(test.name())) {
return true;
}
}
return false;
The enum is:
public enum Test {
A,
B,
}
Also you could return the enum constant or null, since enums are usually small it won't be a performance issue.
Upvotes: 2
Reputation: 23311
You can catch IllegalArgumentException, that will be thrown when a bad value is given.
Upvotes: 1