访问枚举的构造函数中的其他枚举 [英] Access other enums in enum's constructor
问题描述
我需要像下面这样的东西。
I'd need something like the following
enum EE {
A("anything"),
B("beta"),
...
Z("zulu"),
ALL,
;
EE(String s) {
this.s = s;
}
EE() {
String s = "";
for (EE ee : values()) { // PROBLEM HERE
if (ee != ALL) s += " " + ee.s;
}
this.s = s;
}
}
创建 ALL
我想访问枚举的其他成员。由于
values()
返回 null
,所以上述不起作用。使用 A
, B
,..., Z
不编译我完全理解为什么这个鸡蛋问题发生,但是正在寻找一个很好的解决方法。
While creating ALL
I'd like to access the other members of the enum. The above doesn't work because of values()
returning null
at this point. Using A
, B
, ..., Z
explicitly doesn't compile. I understand perfectly why this chicken-egg problem happens, but am looking for a nice workaround.
而不是,删除 ALL
从 EE
不是一个选项。
And no, removing ALL
from EE
is not an option.
推荐答案
你可以一个静态StringBuilder,每个枚举常量将其值附加到构造函数中,然后在默认构造函数中将枚举的字符串设置为StringBuilder的值。
You could have a static StringBuilder that each enum constant appends its value to in the constructor, then in your default constructor just set the enum's string to the value of the StringBuilder.
请注意, Java将阻止您直接从枚举的构造函数访问静态变量(原因很好!),所以您必须在其他方法中执行脏工作,然后从构造函数中调用该变量。
Note however that Java will prevent you accessing static variables directly from an enum's constructor (for good reason!) so you'll have to do the dirty work in another method and then call that from the constructor.
为了工作,虽然你必须确保 ALL
最后被声明。
For this to work though you'll have to make sure ALL
is declared last.
As一个免责声明虽然这是一个真正可怕的解决方法,如果你可以,我鼓励你去探索其他的可能性!
As a disclaimer though this is a truly horrible workaround and if you can at all, I'd encourage you to explore other possibilities here!
这篇关于访问枚举的构造函数中的其他枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!