Changing Enum at Runtime Java

放肆的年华 提交于 2019-12-01 21:11: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.

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.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!