我可以在运行时在 Java 中添加和删除枚举元素吗 [英] Can I add and remove elements of enumeration at runtime in Java

查看:40
本文介绍了我可以在运行时在 Java 中添加和删除枚举元素吗的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可以在运行时在 Java 中从枚举中添加和删除元素吗?

It is possible to add and remove elements from an enum in Java at runtime?

例如,我可以从文件中读取枚举的标签和构造函数参数吗?

For example, could I read in the labels and constructor arguments of an enum from a file?

@saua,这只是一个是否真的可以出于兴趣而做的问题.我希望有一些改变正在运行的字节码的巧妙方法,也许使用 BCEL 或其他东西.我还跟进了这个问题,因为我意识到我不完全确定什么时候应该使用枚举.

@saua, it's just a question of whether it can be done out of interest really. I was hoping there'd be some neat way of altering the running bytecode, maybe using BCEL or something. I've also followed up with this question because I realised I wasn't totally sure when an enum should be used.

如果我希望能够在运行时安全地更改内容,我非常确信正确的答案是使用确保唯一性的集合而不是枚举.

I'm pretty convinced that the right answer would be to use a collection that ensured uniqueness instead of an enum if I want to be able to alter the contents safely at runtime.

推荐答案

不,枚举应该是完整的静态枚举.

No, enums are supposed to be a complete static enumeration.

在编译时,您可能希望从某种其他源文件生成枚举 .java 文件.你甚至可以像这样创建一个 .class 文件.

At compile time, you might want to generate your enum .java file from another source file of some sort. You could even create a .class file like this.

在某些情况下,您可能需要一组标准值但允许扩展.通常的做法是有一个 interface 接口和一个 enum 实现标准值的 interface .当然,当您只有对 interface 的引用时,您就失去了 switch 的能力.

In some cases you might want a set of standard values but allow extension. The usual way to do this is have an interface for the interface and an enum that implements that interface for the standard values. Of course, you lose the ability to switch when you only have a reference to the interface.

这篇关于我可以在运行时在 Java 中添加和删除枚举元素吗的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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