Skip to content

Instantly share code, notes, and snippets.

@ankushs92
Created April 16, 2016 17:15
Show Gist options
  • Save ankushs92/246fdab7e49904add73f1c9ef3cdb769 to your computer and use it in GitHub Desktop.
Save ankushs92/246fdab7e49904add73f1c9ef3cdb769 to your computer and use it in GitHub Desktop.
Convert a String to an Enumeration (if possible).
public class EnumUtils {
public static <T extends Enum<T>> T getEnumFromString(final Class<T> enumClass,final String value) {
if(enumClass == null){
throw new IllegalArgumentException("enumClass cannot be null");
}
for (final Enum<?> enumValue : enumClass.getEnumConstants()) {
if (enumValue.toString().equalsIgnoreCase(value)) {
return (T) enumValue;
}
}
//Construct an error message that indicates all possible values for the enum.
final StringBuilder errorMessage = new StringBuilder();
boolean bFirstTime = true;
for (final Enum<?> enumValue : enumClass.getEnumConstants()) {
errorMessage.append(bFirstTime ? "" : ", ").append(enumValue);
bFirstTime = false;
}
throw new IllegalArgumentException(value + " is invalid value. Supported values are " + errorMessage);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment