Java - Create enum instances dynamically
by Jerome Kehrli
Posted on Saturday Nov 13, 2010 at 09:08PM in Java
I remember the introduction of the brand new enum type in Java 5 (1.5) was a very exciting announce. However, when I finally switched from 1.4 to 1.5 and actually tried Java's flavoured enum types, I was a bit disappointed.
Before that, I was using Josh Bloch's "Typesafe enum" pattern (effective java) for quite a long time and I didn't really see what was so much better with the new Java native enum construction. Ok, fine, there was the ability to use enum instances in
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.
- 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 in
java.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 in
java.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 the
java.lang.Classinstance caches are cleared as well.
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 :
makeEnum method uses another method named
getConstructorAccessor to obtain a reference on the constructor accessor allowing to actually create the new enum instance :
setFailsafeFieldValue(Field field, Object target, Object value) throws NoSuchFieldException, IllegalAccessException
This 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 :
cleanEnumCache(Class<?> enumClass) throws NoSuchFieldException, IllegalAccessException
This method clears the enum cache variable on two different JVM implementations.
It used the
blankField method to actually blank the target field :
On can test this dynamic enum instance adding system using the following little code snippet:
The complete code presented in this article is available here : DynamicEnumTest.java
Interestingly, this is a situation where runtime reflection, as limited as it is, is yet sufficient for the few required manipulations involved in this dynamic enum creation feature. It would be interesting to see how a much more powerful mechanism such as javassist (bytecode manipulation) could make things easier. Maybe I'll dig into it someday ...