Changing Enum at Runtime Java

后端 未结 2 453
花落未央
花落未央 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.

提交回复
热议问题