Let’s say I have a file whose format is basic XML, like so:
<?xml version="1.0"?>
<enum-set>
<enum>
<name>SomeEnum</name>
<values>
<value>
<name>SOMEVALUE</name>
<displayText>This is some value</displayText>
</value>
... more values ...
</values>
</enum>
... more enums ...
</enum-set>
and I wanted to turn SomeEnum into something like this at runtime:
public enum SomeEnum implements HasDisplayText {
SOMEVALUE("This is some value"),
... more values ...;
private String displayText;
SomeEnum(String displayText) {
this.displayText = displayText;
}
@Override
public String getDisplayText() {
return displayText;
}
}
… and then pass the newly created enum SomeEnum around my application. How might I achieve something like this? Is it doable?
What you’re trying to do doesn’t make a whole lot of sense. Enums are really only for the benefit of compile time, as they represent a fixed set of constants. At runtime, what would be the meaning of a dynamically generated enum – how would this be different from an plain object? For example:
Your XML could be parsed into newly instantiated
Salutationobjects, which could be stored in someCollectionor otherwise used by your program. Notice in my example, I’ve restricted the creation ofSalutationby giving it aprivateconstructor – in this case the only way to retrieve instances is by calling the factory method which takes your XML. I believe this achieves the behavior you’re looking for.