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
Getoutputstream() Has Already Been Called for This Response
How to Read Jsch Command Output
How to Change JPAnel Inside a Jframe on the Fly
How to Iterate an Arraylist Inside a Hashmap Using Jstl
How to Understand Happens-Before Consistent
Is Java.Time Failing to Parse Fraction-Of-Second
Jersey /* Servlet Mapping Causes 404 Error for Static Resources
Integer Wrapper Class and == Operator - Where Is Behavior Specified
Java - Transparent Jscrollpane
Why Double Width = 50/110000; the Output Is 0.000000000000000
What Does "Error: '.Class' Expected" Mean and How to Fix It
Jlabel Mouse Events for Drag and Drop
What Happens When I Throw a C++ Exception from a Native Java Method
How to Get Rjava 0.9-3 to Work on Os X 10.7.4 with Oracle Java 1.7
What's the Best Mock Framework for Java
Using Java 8's Optional with Stream::Flatmap
Why Java Inner Classes Require "Final" Outer Instance Variables