switch - case statements which seemed fine, but what else ?
Besides, what I used to find great with the "typesafe enum" pattern is that it could be tricked and changed the way I wanted, for instance to be able to dynamically (at runtime) add enum instances to a specific typesafe enum class. I found it very disappointing not to be able to do the very same thing easily with the native Java enum construction.
And now you might wonder "Why the hell could one ever need to dynamically add enum values ?!?". You do, right ? Well, let's imagine this scenario:
You have a specific column in a DB table which contains various codes as values. There are more than hundred different codes actually in use in this column. Related to this, you have a business logic which performs different operations on the rows coming from this table, the actual kind of operation applied on the row depends on the value of this code. So there are chance you end up with a lot of if - elseif statements checking the actual value of the code. I myself am allergic to using string comparison in conditions so I want to be able to map the values from this column to an enum type in Java. This way I can compare enum values instead of strings in my conditions and reduce my dependency on the format of the string value. Now when there are more than a hundred different possible codes in the DB I really don't have any intent to define them all manually in my enum type. I want to define only the few I am actually using the Java code and let the system add the other ones dynamically, at runtime, when it (the ORM system or whatever I am using for reading the DB rows) encounters a new value from the DB. Hence my need for dynamically added enum values. So recently I faced this need once again and took a few hours to build a little solution which enables one to dynamically add values to a Java enum type. The solution is the following : (Complete code here : DynamicEnumTest.java)
void addEnum(Class<T> enumType, String enumName)This method adds an enum instance to the enum type given as argument. The whole method code is presented below. We will first details its behaviour and then present every other method this one is using./**
* Add an enum instance to the enum class given as argument
*
* @paramthe type of the enum (implicit)
* @param enumType the class of the enum to be modified
* @param enumName the name of the new enum instance to be added to the class.
*/
@SuppressWarnings("unchecked")
public static <T extends Enum<?>> void addEnum(Class<T> enumType, String enumName) {
// 0. Sanity checks
if (!Enum.class.isAssignableFrom(enumType)) {
throw new RuntimeException("class " + enumType + " is not an instance of Enum");
}
// 1. Lookup "$VALUES" holder in enum class and get previous enum instances
Field valuesField = null;
Field[] fields = TestEnum.class.getDeclaredFields();
for (Field field : fields) {
if (field.getName().contains("$VALUES")) {
valuesField = field;
break;
}
}
AccessibleObject.setAccessible(new Field[] { valuesField }, true);
try {
// 2. Copy it
T[] previousValues = (T[]) valuesField.get(enumType);
Listvalues = new ArrayList (Arrays.asList(previousValues));
// 3. build new enum
T newValue = (T) makeEnum(enumType, // The target enum class
enumName, // THE NEW ENUM INSTANCE TO BE DYNAMICALLY ADDED
values.size(),
new Class<><[] {}, // can be used to pass values to the enum constuctor
new Object[] {}); // can be used to pass values to the enum constuctor
// 4. add new value
values.add(newValue);
// 5. Set new values field
setFailsafeFieldValue(valuesField, null,
values.toArray((T[]) Array.newInstance(enumType, 0)));
// 6. Clean enum cache
cleanEnumCache(enumType);
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e.getMessage(), e);
}
}- The enum instances are stored in a static variable of the enum class named
$VALUES. Here we search for this static variable, make it accessible and keep the reference for further usage. - The enum instances contained in the
$VALUESstatic variable are copied (stored) in another (new) list. - Then the new enum instance is built using another method named
makeEnumwhich will be discussed later. - The new enum instance is added to the new enum list.
- The new enum instance list (containin the new enum instance) is set to the
$VALUESfield, overwriting the previous content. - The cleaning of the cache answers to something special and tricky. The problem is that the
$VALUESis purely generated by the compiler. So the static java code located injava.lang.Classcannot be statically linked to it. Hence it needs to access$VALUESvariable using runtime reflection which is a little costy (compared to static method call linking). Hence the code injava.lang.Classwhich needs an access to the enum values makes a copy of them upon first usage in a private instance variable, the enum cache
Thus, adding the new enum instance in the$VALUESlist is not sufficient, one needs to make sure thejava.lang.Classinstance caches are cleared as well.
- The enum instances are stored in a static variable of the enum class named
Object makeEnum(Class<?> enumClass, String value, int ordinal, Class<?>[] additionalTypes, Object[] additionalValues)This method creates the new enum instance. It takes as argument the class for which to create a new enum instance and the name of the enum instance to create. The ordinal argument is the ordinal value which will be associated to the enum instance. The two last arrays are helpful if on want to add an enum instance to an enum type using constructor arguments to store values bound to the enum instances. The details of the method is as follows :Theprivate static Object makeEnum(Class<?> enumClass, String value, int ordinal,
Class<?>[] additionalTypes, Object[] additionalValues) throws Exception {
Object[] parms = new Object[additionalValues.length + 2];
parms[0] = value;
parms[1] = Integer.valueOf(ordinal);
System.arraycopy(additionalValues, 0, parms, 2, additionalValues.length);
return enumClass.cast(getConstructorAccessor(enumClass, additionalTypes).newInstance(parms));
}
makeEnummethod uses another method namedgetConstructorAccessorto obtain a reference on the constructor accessor allowing to actually create the new enum instance :private static ConstructorAccessor getConstructorAccessor(Class<?> enumClass,
Class<?>[] additionalParameterTypes) throws NoSuchMethodException {
Class<?>[] parameterTypes = new Class[additionalParameterTypes.length + 2];
parameterTypes[0] = String.class;
parameterTypes[1] = int.class;
System.arraycopy(additionalParameterTypes, 0,
parameterTypes, 2, additionalParameterTypes.length);
return reflectionFactory.newConstructorAccessor(
enumClass.getDeclaredConstructor(parameterTypes));
}setFailsafeFieldValue(Field field, Object target, Object value) throws NoSuchFieldException, IllegalAccessExceptionThis method is a convenient method whose responsibility is to set the value given as argument to the field given as argument on the target given as argument. This sounds easy yet doing in failsafely is a little bit more tricky than one could guess :private static void setFailsafeFieldValue(Field field, Object target, Object value)
throws NoSuchFieldException, IllegalAccessException {
// let's make the field accessible
field.setAccessible(true);
// next we change the modifier in the Field instance to
// not be final anymore, thus tricking reflection into
// letting us modify the static final field
Field modifiersField = Field.class.getDeclaredField("modifiers");
modifiersField.setAccessible(true);
int modifiers = modifiersField.getInt(field);
// blank out the final bit in the modifiers int
modifiers &= ~Modifier.FINAL;
modifiersField.setInt(field, modifiers);
FieldAccessor fa = reflectionFactory.newFieldAccessor(field, false);
fa.set(target, value);
}
-
This method clears the enum cache variable on two different JVM implementations.cleanEnumCache(Class<?> enumClass) throws NoSuchFieldException, IllegalAccessExceptionIt used theprivate static void cleanEnumCache(Class<?> enumClass)
throws NoSuchFieldException, IllegalAccessException {
blankField(enumClass, "enumConstantDirectory"); // Sun (Oracle?!?) JDK 1.5/6
blankField(enumClass, "enumConstants"); // IBM JDK
}
blankFieldmethod to actually blank the target field :private static void blankField(Class<?> enumClass, String fieldName)
throws NoSuchFieldException, IllegalAccessException {
for (Field field : Class.class.getDeclaredFields()) {
if (field.getName().contains(fieldName)) {
AccessibleObject.setAccessible(new Field[] { field }, true);
setFailsafeFieldValue(field, enumClass, null);
break;
}
}
}
-
private static enum TestEnum {
a,
b,
c;
};
public static void main(String[] args) {
// Dynamically add 3 new enum instances d, e, f to TestEnum
addEnum(TestEnum.class , "d");
addEnum(TestEnum.class , "e");
addEnum(TestEnum.class , "f");
// Run a few tests just to show it works OK.
System.out.println(Arrays.deepToString(TestEnum.values()));
// Shows : [a, b, c, d, e, f]
}
Posted by 122.181.131.76 on mai 26, 2011 at 05:27 AM CEST #
Posted by cindy on juin 04, 2011 at 04:53 AM CEST #
Posted by Aman on novembre 29, 2011 at 06:08 AM CET #
Posted by Naveed on juin 29, 2012 at 11:14 AM CEST #
First you need to get access to the "Field" instance representing your enum object property.
An example is available in the niceideas-commons library here :
http://niceideas.ch/niceideas-commons-1.1-beta-0.1-apidocs/src-html/ch/niceideas/common/utils/ReflectionUtils.html#line.434
Then, once you have the "Field" instance, you can set it to any value, including "null".
An example is again available in the niceideas-commons library here :
http://niceideas.ch/niceideas-commons-1.1-beta-0.1-apidocs/src-html/ch/niceideas/common/utils/ReflectionUtils.html#line.646
Posted by badtrash on juillet 04, 2012 at 09:19 AM CEST #