在运行时Java更改枚举 [英] Changing Enum at Runtime Java

查看:218
本文介绍了在运行时Java更改枚举的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我的问题类似于我可以在Java的运行时添加和删除枚举的元素,但是问题似乎是为了构建你自己的枚举,然后修改它。我假设有一个现有的枚举,我不能改变,像

 枚举天{MONDAY,TUESDAY,WEDNESDAY} 

,我想添加星期四,星期五等。不幸的是,如何使用界面来完成我的目标,或其他比枚举更有效的方法的建议不适用于这里。



据了解它,枚举是隐含的最终的,所以我不能扩展它,并添加更多的元素。它有私人领域,但似乎我可以使用反射来访问那些 - 我可以更改一个私人领域,即使我不能添加一个新的,即更改星期一到星期四?



编辑:澄清情况



人们建议在编译程序之前更改代码。我的代码是一个更大的项目的一部分,我不能改变;在它的类访问它之前,其中包含枚举的类被较大的程序加载。在这一点上,我想将缺少的元素添加到枚举中。字符代码的操作还有待改进吗?

解决方案

枚举是静态的,最终的,不可变的,实例控制的对象有常数感。您应该在您的项目中包含一个自然分组或在编译时已知的东西的列表时,应该考虑一个枚举。



JVM保证枚举是实例控制的,在运行时不可变。枚举的二进制兼容性也是保证的,所以如果以后添加枚举常量,你的程序将继续运行。



简短的答案是:不,在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?

解决方案

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.

这篇关于在运行时Java更改枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆