Create an enum dynamically


(Recovered from my old Blog).

When creating an enum dynamically, there are two levels of difficulty.

The first case is where the type of the enum is known at compile-time, but the value is not. In this case, we can use the valueOf method of the enum in question:

The second, more complex case is where neither the type nor the value is known. The Enum base class (from whence all enums derive) contains a static method for this scenario:

This can result in Unchecked Invocation warnings so either proper checking will be required, or a suppression of the warning if absolutely sure.

In cases involving generics, it will be required to cast this call to prevent the “Bound mismatch” exception (essentially the compiler forcing the generic to be an implementation of Enum, which of course it must be since all enumerations derive from Enum).


Leave a Reply

Your email address will not be published. Required fields are marked *

%d bloggers like this: