Created
April 16, 2016 17:15
-
-
Save ankushs92/246fdab7e49904add73f1c9ef3cdb769 to your computer and use it in GitHub Desktop.
Convert a String to an Enumeration (if possible).
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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