Created
December 13, 2017 18:08
-
-
Save ashwinrs/262271a26f8c251c2779377318957ee4 to your computer and use it in GitHub Desktop.
Gets enum from a string
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
/** | |
* 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