The previous answers by dariosicily and marc cover most of the ground. But I have a few other comments.
- If you go for more meaningful names for your enum values, you
probably don't need a "status" field - you can simply map the name to
lower case.
- I'm not sure UnsupportedOperationException is the best choice here, and can see no good reason not to create your own Exception for the purpose.
- If your list of enum values grows significantly bigger, I'd suggest maintaining a Map of the values rather than doing a sequential search. My example below does this, just to illustrate how I'd do that, though for three values it's probably overkill.
package codeReview;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import codeReview.Penzov.BusinessCustomersStatus.NoSuchStatusException;
public class Penzov {
public enum BusinessCustomersStatus {
ACTIVE, //
ONBOARDING, //
NOT_VERIFIED;
static Map <String,BusinessCustomersStatus> statusLookup = new HashMap<>();
static {
for (BusinessCustomersStatus status: values()) {
statusLookup.put(status.getStatus(), status);
}
}
public String getStatus() {
return name().toLowerCase();
}
public static BusinessCustomersStatus getStatusByText(String statusText) throws NoSuchStatusException {
BusinessCustomersStatus status = statusLookup.get(statusText.toLowerCase());
if (status != null) {
return status;
}
// Didn't find a match
throw new NoSuchStatusException(String.format("Unknown status: '%s'", statusText));
}
public static class NoSuchStatusException extends Exception {
private static final long serialVersionUID = -2003653625428537073L;
public NoSuchStatusException(String message) {
super(message);
}
}
}
public static void main(String[] args) {
for (String testString: Arrays.asList("active", "ONBOARDING", "NoT_VERified", "dubious")) {
try {
System.out.format("testString = '%s', status found = '%s'%n", testString, BusinessCustomersStatus.getStatusByText(testString));
} catch (NoSuchStatusException e) {
System.out.format("testString = '%s', exception thrown = '%s'%n", testString, String.valueOf(e));
}
}
}
}