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
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With