Generating Enums Dynamically

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:

public class Salutation implements HasDisplayText {

   private String displayText;

   private Salutation(String displayText) {
       this.displayText = displayText;
   }

   @Override
   public String getDisplayText() {
       return displayText;
   }

   public static Collection<Salutation> loadSalutations(String xml) {
      //parse, instantiate, and return Salutations
   }
}

Your XML could be parsed into newly instantiated Salutation objects, which could be stored in some Collection or otherwise used by your program. Notice in my example, I’ve restricted the creation of Salutation by giving it a private constructor – 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.

Leave a Comment