Skip to content

Instantly share code, notes, and snippets.

@cushon
Last active August 29, 2015 13:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cushon/9940204 to your computer and use it in GitHub Desktop.
Save cushon/9940204 to your computer and use it in GitHub Desktop.
For when you absolutely positively have to create an enum.
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