Last active
August 29, 2015 13:58
-
-
Save cushon/9940204 to your computer and use it in GitHub Desktop.
For when you absolutely positively have to create an enum.
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
static <T extends Enum<T>> T getOrCreateEnum(Class<T> enumType, | |
String name, int ordinal) { | |
try { | |
return Enum.valueOf(enumType, name); | |
} catch (IllegalArgumentException createFascimileInstead) { | |
} | |
try { | |
T enumValue = (T) getUnsafe().allocateInstance(enumType); | |
Field nameField = Enum.class.getDeclaredField("name"); | |
nameField.setAccessible(true); | |
nameField.set(enumValue, name); | |
Field ordinalField = Enum.class.getDeclaredField("ordinal"); | |
ordinalField.setAccessible(true); | |
ordinalField.set(enumValue, ordinal); | |
return enumValue; | |
} catch (SecurityException e) { | |
// return null for degraded results. | |
return null; | |
} catch (ReflectiveOperationException e) { | |
throw new LinkageError(e.toString()); | |
} | |
} | |
static Unsafe getUnsafe() { | |
try { | |
return Unsafe.getUnsafe(); | |
} catch (SecurityException tryReflectionInstead) { | |
} | |
try { | |
Field theUnsafeField = Unsafe.class.getDeclaredField("theUnsafe"); | |
theUnsafeField.setAccessible(true); | |
return (Unsafe) theUnsafeField.get(null); | |
} catch (ReflectiveOperationException e) { | |
throw new LinkageError(e.toString()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment