javaenumsexpandable

Expandable enum Java


I'm making a program that has an enum that us used for a list of types but I want it to have the possibility of being expanded later at runtime and am not sure what is the best way to do this is. The only ways I have been able to think of are using arrays of classes in place of the enum which I don't want to do as I would loose the simplicity of the enum.


Solution

  • Enums are supposed to be completely static enumerations, therefore you must be able to know the exact values the enum covers at compile time.

    You could generate the java file at compile time allowing for a bit more flexibility over the values, although this would be rather over the top.

    Your best bet would be:

    1) To use a class, potentially with a set of predefined instances, so that new instance of said class can be created at runtime.

    or

    2) To create an interface that an enum containing the default values implements, allowing new instances to be created at runtime, whilst retaining some form of enum structure.