Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing Enum at Runtime Java

Is there any way to add elements to a built in enum class in Java?

My question is similar to Can I add and remove elements of enumeration at runtime in Java, but that question seems to be geared towards constructing your own enum and then modifying it. I'm assuming there's an existing enum somewhere I can't change, something like

enum Days{ MONDAY, TUESDAY, WEDNESDAY }

and I want to add Thursday, Friday, etc. to it. So unfortunately, suggestions of how to use an interface to accomplish my goal, or other methods that would be more effective than enums, don't apply here.

As I understand it, enums are implicitly final, so I can't extend it and add more elements to it. It has private fields, but it appears I can use reflection to access those - could I change one of the private fields, even if I can't add a new one, i.e, change Monday to Thursday?

Edit: Clarification of Circumstances

People have suggested altering the code before it's compiled into the program. My code is part of a larger project that I can't change; the class with the enum in it is loaded by the larger program before my class gets access to it. At that point, I'd like to add the missing elements to the enum. Is bytecode manipulation still the way to go?

like image 979
en_Knight Avatar asked May 25 '26 11:05

en_Knight


1 Answers

Enums are intended to be static, final, immutable, instance-controlled objects that have the sense of constants. You should think of an enum any time your project contains a natural grouping or listing of things that are known at compile time.

The JVM guarantees that enums are instance-controlled and immutable at run-time. The binary compatibility of enums is also guaranteed so that if, later on, you add enum constants, your programs will continue to run.

The short answer is: "no, there is no easy way to extend an enum class in java."

One alternative is to have a base enum implement an interface that serves as the base type for the enum constants.

It is then possible to "extend" the enum by creating a new enum that implements the interface. Even so, this is not something that, by design, was ever intended to take place at run time.

like image 64
scottb Avatar answered May 28 '26 01:05

scottb



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!