Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validate successful String to enum conversion in Java

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
}
like image 838
Dima Avatar asked Jun 22 '12 19:06

Dima


1 Answers

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.

like image 109
Juan Alberto López Cavallotti Avatar answered Sep 29 '22 06:09

Juan Alberto López Cavallotti