访问枚举构造函数中的其他枚举
我需要类似以下的东西
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
,因此上述操作null
。 使用A
, B
,…, Z
显式不编译。 我完全理解为什么会发生鸡蛋问题,但我正在寻找一个很好的解决方法。
不,从EE
删除ALL
不是一种选择。
您可以拥有一个静态StringBuilder,每个枚举常量将其值附加到构造函数中,然后在默认构造函数中将enum的字符串设置为StringBuilder的值。
但请注意,Java会阻止您直接从枚举构造函数中访问静态变量(理由充分!),因此您必须在另一个方法中执行脏工作,然后从构造函数中调用它。
为了使这个工作,你必须确保ALL
被最后声明。
作为免责声明虽然这是一个真正可怕的解决方法,如果你可以,我鼓励你在这里探索其他可能性!
这对你有用吗? :
enum EE { A("anything"), B("beta"), ... Z("zulu"), ALL, ; String s = null; EE(String s) { this.s = s; } EE() { } private void initS() { String s = ""; for (EE ee : values()) { if (ee != ALL) s += " " + ee.s; } this.s = s; } public String getS() { if ( this.s == null ) { // assume we are ALL and initialize initS(); } return this.s; } }
静态初始化程序可能更清晰。
public enum EE { A("anything"), B("beta"), Z("zulu"), ALL ; static { String s = ""; for (EE ee : values()) { if ( ee != ALL ) s += ee + " "; } ALL.s = s.trim(); } String s = null; EE(String s) { this.s = s; } EE() { } }
最好的方法之一是使用enum polymorphism technique
:
public enum EE { A("anything"), B("beta"), Z("zulu"), ALL { @Override public String getS() { if (super.s == null) { String s = ""; for (EE ee : values()) { if (ee != ALL) { s += " " + ee.s; } } } return s; } }, ; private String s; EE(String s) { this.s = s; } EE() { this.s = null; } public String getS() { return this.s; } }
测试类:
public class TestEE { public static void main(String[] args) { for (EE ee : EE.values()) { System.out.println(ee.name() + ": " + ee.getS()); } } }
也可以看看:
- 重写抽象枚举方法
为什么你不能删除所有?
考虑使用EnumSet ,这将为您提供EE的任意组合。
import java.util.*; enum EE { A("anything"), B("beta"), Z("zulu"); EE(String s) { this.s = s; } static Set all=EnumSet.allOf(EE.class); final String s; }