访问枚举构造函数中的其他枚举

maa*_*nus 4 java oop enums initialization

我需要类似以下的东西

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

创建时ALL我想访问枚举的其他成员.由于此时values()返回null,上述方法无效.使用A,, B... Z显式不编译.我完全理解为什么这个鸡蛋问题会发生,但我正在寻找一个很好的解决方法.

不,ALL从中删除EE不是一种选择.

Mih*_*der 5

这对你有用吗?:

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

静态初始化程序可能更清晰.

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() {
    }
}
Run Code Online (Sandbox Code Playgroud)