Changing Enum at Runtime Java

后端 未结 2 434
花落未央
花落未央 2021-01-20 02:08

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 tha

相关标签:
2条回答
  • 2021-01-20 02:26

    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.

    0 讨论(0)
  • 2021-01-20 02:34

    You can change a enum at runtime my altering the class at runtime before you load it. You can either compile an altered enum at runtime and load it or you can use byte code manipulation to alter it.

    In short, include all the enums you need and you should never need to add to them at runtime. e.g. if there are only seven days in a weeks, include all of them at compile time.

    0 讨论(0)
提交回复
热议问题