动态生成枚举 [英] Generating Enums Dynamically
问题描述
假设我有一个格式为基本XML的文件,如下所示:
Let's say I have a file whose format is basic XML, like so:
<?xml version="1.0"?>
<enum-set>
<enum>
<name>SomeEnum</name>
<values>
<value>
<name>SOMEVALUE</name>
<displayText>This is some value</displayText>
</value>
... more values ...
</values>
</enum>
... more enums ...
</enum-set>
我想将 SomeEnum
变成某种东西在运行时是这样的:
and I wanted to turn SomeEnum
into something like this at runtime:
public enum SomeEnum implements HasDisplayText {
SOMEVALUE("This is some value"),
... more values ...;
private String displayText;
SomeEnum(String displayText) {
this.displayText = displayText;
}
@Override
public String getDisplayText() {
return displayText;
}
}
...,然后传递新创建的枚举 SomeEnum
。我将如何实现这样的目标?
... and then pass the newly created enum SomeEnum
around my application. How might I achieve something like this? Is it doable?
推荐答案
您尝试执行的操作没有任何意义。 枚举实际上仅是为了编译时,因为它们代表一组固定的常数。在运行时,动态生成的枚举的含义是什么-与普通对象有什么不同?例如:
What you're trying to do doesn't make a whole lot of sense. Enums are really only for the benefit of compile time, as they represent a fixed set of constants. At runtime, what would be the meaning of a dynamically generated enum - how would this be different from an plain object? For example:
public class Salutation implements HasDisplayText {
private String displayText;
private Salutation(String displayText) {
this.displayText = displayText;
}
@Override
public String getDisplayText() {
return displayText;
}
public static Collection<Salutation> loadSalutations(String xml) {
//parse, instantiate, and return Salutations
}
}
您的XML可以解析为新实例化的 Salutation
对象,这些对象可以存储在某些 Collection $ c $中c>或您的程序使用的其他方式。请注意,在我的示例中,我通过给
private
构造函数限制了 Salutation
的创建-在这种情况下,检索实例的唯一方法是调用采用XML的factory方法。我相信这可以达到您想要的行为。
Your XML could be parsed into newly instantiated Salutation
objects, which could be stored in some Collection
or otherwise used by your program. Notice in my example, I've restricted the creation of Salutation
by giving it a private
constructor - in this case the only way to retrieve instances is by calling the factory method which takes your XML. I believe this achieves the behavior you're looking for.
这篇关于动态生成枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!