How to Add and Remove Elements of Enumeration at Runtime in Java

Can I add and remove elements of enumeration at runtime in Java

No, enums are supposed to be a complete static enumeration.

At compile time, you might want to generate your enum .java file from another source file of some sort. You could even create a .class file like this.

In some cases you might want a set of standard values but allow extension. The usual way to do this is have an interface for the interface and an enum that implements that interface for the standard values. Of course, you lose the ability to switch when you only have a reference to the interface.

How to add values to an existing enums outside of the class in java

The enum should be defined in compile time. yo can not change enum at run time.

You can use a List<String> or a Map<String,integer> and using simple string literals to simulate a dynamic enumeration.

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.

Create enum while running an application

You cannot create enums at runtime. Enums present a fixed constant, you must define them in source code.



Related Topics



Leave a reply



Submit