Skip to content

Instantly share code, notes, and snippets.

@ashwinrs
Created December 13, 2017 18:08
Show Gist options
  • Save ashwinrs/262271a26f8c251c2779377318957ee4 to your computer and use it in GitHub Desktop.
Save ashwinrs/262271a26f8c251c2779377318957ee4 to your computer and use it in GitHub Desktop.
Gets enum from a string
/**
* A common method for all enums since they can't have another base class
* @param <T> Enum type
* @param c enum type. All enums must be all caps.
* @param string case insensitive
* @return corresponding enum, or null
*/
public static <T extends Enum<T>> T getEnumFromString(Class<T> c, String string) {
if( c != null && string != null ) {
try {
return Enum.valueOf(c, string.trim().toUpperCase());
} catch(IllegalArgumentException ex) {
}
}
return null;
}
// Usage
public static MyEnum fromString(String name) {
return getEnumFromString(MyEnum.class, name);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment