枚举的 toString 中的默认大小写

Default case in toString for enums

我对 Java 中的枚举有些陌生,我正在尝试覆盖 toString() 以便它可以 return 枚举的特殊情况,并为每种情况创建代码:

enum TestEnum {
One, Two, Three,
Exclamation, Ampersand, Asterisk;

public String toString() {
    if (this == Ampersand) return "&";
    if (this == Exclamation) return "!";
    if (this == Asterisk) return "*";
    return null; // return toString(); ???
}

如果我使用 toString 作为默认的 return 语句,我显然会得到 WhosebugError。有没有办法解决这个问题以及 return 任何未包含在 toString() 中的情况?

Is there a way to get around this and return any cases not included in the toString()?

我想你只是想要:

return super.toString();

然后它不会调用自己 - 它只会使用超类实现。

但是,我会更改实现,使字符串表示成为枚举值中的一个字段,必要时在构建时指定:

enum TestEnum {
    One, Two, Three,
    Exclamation("!"), Ampersand("&"), Asterisk("*");

    private final String name;

    private TestEnum(String name) {
        this.name = name;
    }

    private TestEnum() {
        name = super.toString();
    }

    @Override public String toString() {
        return name;
    }
}

测试:

public class Test {
    public static void main(String [] args){
        for (TestEnum x : TestEnum.values()) {
            System.out.println(x);
        }
    }
}

输出:

One
Two
Three
!
&
*