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

查看:90
本文介绍了我可以在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.

在某些情况下,您可能需要一组标准值,但允许扩展。通常的方法是为接口提供一个接口,并实现一个枚举,实现界面为标准值。当然,当您仅引用接口时,您将失去开关的功能。

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天全站免登陆