Enum Tricks: Dynamic Enums
Join the DZone community and get the full member experience.
Join For FreeIntroduced to Java 1.5, Enum is a very useful and well known feature. There are a lot of tutorials that explain enums usage in details (e.g. the official Sun’s tutorial). Java enums by definition are immutable and must be defined in code. In this article I would like to explain use case when dynamic enums are needed and how to implement them.
Motivation
There are 3 ways to use enums:
- direct access using the enum value, e.g. Color.RED
- access using enum name, e.g. Color.valueOf("RED")
- get enumeration of all enum values using values() method, e.g. Color.values()
Sometimes it is very convenient to store some information about enum in DB, file etc. In this case the enum defined in code must contain appropriate values.
For example let’s discover the enum Color:
enum Color {RED, GREEN, BLUE;}
Let’s assume that we would like to allow user to create his custom colors. So, we have to handle the table “Color” in database. But in this case we cannot continue using enum Color: if user adds new color (e.g. YELLOW) to DB we have to modify code and add this color to enum too.
OK, we can refuse to use enum in this case. Just rename enum to class and initialize list of colors from DB. But what if we already have 100 thousand lines of code where methods values() and valueOf() of enum Color are used? No problem: we can implement valueOf() and values() manually for the new class “Color.”
Now we see the problem. What if we have to refactor 12 enums like Color? Copy/Paste the new methods to all these classes? I would like to suggest other, more generic approach.
Making enums dynamic
Enum is compile time feature. When we create enum Foo, class Foo that extends java.lang.Enum is generated for us automatically. This is the reason that enum cannot extend other class (multiple inheritance is not supported in Java). Moreover some compiler magic prevents any attempt to manually write a class that extends java.lang.Enum.
The only solution is to write yet another class similar to Enum. I wrote class DynaEnum. This class mimics functionality of Enum but it is regular class, so it can be inherited. A static hash table holds elements of all created dynamic enums.
My DynaEnum contains a generic implementation of valueOf() and values() done using reflection, so users of this class do not have to implement them.
This class allows relatively easy refactoring for use case described above. Just change enum to class, inherit it from DynaEnum and write code to initialize members.
Example
Source code of the examples can be found here.
I implemented two examples: DigitsDynaEnum that does not have any added value relative to enum. It is implemented mostly to check that the base class functionality works. DigitsDynaEnumTest contains several unit tests.
package com.alexr.dynaenum; public class DigitsDynaEnum extends DynaEnum<DigitsDynaEnum> { public final static DigitsDynaEnum ZERO = new DigitsDynaEnum("ZERO", 0); public final static DigitsDynaEnum ONE = new DigitsDynaEnum("ONE", 1); public final static DigitsDynaEnum TWO = new DigitsDynaEnum("TWO", 2); public final static DigitsDynaEnum THREE = new DigitsDynaEnum("THREE", 3); protected DigitsDynaEnum(String name, int ordinal) { super(name, ordinal); } public static <E> DynaEnum<? extends DynaEnum<?>>[] values() { return values(DigitsDynaEnum.class); } }
PropertiesDynaEnum is a dynamic enum that reads its members from properties file. Its subclass, WritersDynaEnum, reads a list of famous writers from a properties file WritersDynaEnum.properties.
package com.alexr.dynaenum; import java.io.BufferedReader; import java.io.InputStreamReader; import java.lang.reflect.Constructor; public class PropertiesDynaEnum extends DynaEnum<PropertiesDynaEnum> { protected PropertiesDynaEnum(String name, int ordinal) { super(name, ordinal); } public static <E> DynaEnum<? extends DynaEnum<?>>[] values() { return values(PropertiesDynaEnum.class); } protected static <E> void init(Class<E> clazz) { try { initProps(clazz); } catch (Exception e) { throw new IllegalStateException(e); } } private static <E> void initProps(Class<E> clazz) throws Exception { String rcName = clazz.getName().replace('.', '/') + ".properties"; BufferedReader reader = new BufferedReader(new InputStreamReader(Thread.currentThread().getContextClassLoader().getResourceAsStream(rcName))); Constructor<E> minimalConstructor = getConstructor(clazz, new Class[] {String.class, int.class}); Constructor<E> additionalConstructor = getConstructor(clazz, new Class[] {String.class, int.class, String.class}); int ordinal = 0; for (String line = reader.readLine(); line != null; line = reader.readLine()) { line = line.replaceFirst("#.*", "").trim(); if (line.equals("")) { continue; } String[] parts = line.split("\\s*=\\s*"); if (parts.length == 1 || additionalConstructor == null) { minimalConstructor.newInstance(parts[0], ordinal); } else { additionalConstructor.newInstance(parts[0], ordinal, parts[1]); } } } @SuppressWarnings("unchecked") private static <E> Constructor<E> getConstructor(Class<E> clazz, Class<?>[] argTypes) { for(Class<?> c = clazz; c != null; c = c.getSuperclass()) { try { return (Constructor<E>)c.getDeclaredConstructor(String.class, int.class, String.class); } catch(Exception e) { continue; } } return null; } }
The goal is implemented! We have class that mimics functionality of enum but is absolutely dynamic. We can change list of writers without re-compiling the code. Therefore we can actually store the enum values everywhere and change “enums” at runtime.
It is not a problem to implement something like “JdbcDynaEnum” that reads values from database but this implementation is out of scope of this article.
Limitations
The solution is not ideal. It uses static initialization that could cause problems in multi-class loaders environment. Members of dynamic enums obviously cannot be accessed directly (Color.RED) but only using valueOf() or values(). But still in some cases this technique may be very useful.
Conclusions
Java enum is a very powerful feature but it has serious limitations. Enum values are static and have to be defined in code. This article suggests trick that allows to mimic enum functionality and store “enum” values separately from code.
Opinions expressed by DZone contributors are their own.
Comments