Java枚举类可以设置默认值吗

yel*_*g99 1 java enums

我的代码是

\n\n
public enum PartsOfSpeech2 {\n\n    n("noun"),\n    wp("\xe6\xa0\x87\xe7\x82\xb9"),\n    a("adjective"),\n    d("conjunction"),\n    ...;\n
Run Code Online (Sandbox Code Playgroud)\n\n

我想要哪个

\n\n
public enum PartsOfSpeech2 {\n\n    n("noun"),\n    wp("\xe6\xa0\x87\xe7\x82\xb9"),\n    a("adjective"),\n    d("conjunction"),\n    %("noun");\n
Run Code Online (Sandbox Code Playgroud)\n\n

我可以有一个不在其中的默认值\xef\xbc\x8c 可以将其设置为默认值\xef\xbc\x9f\n因为我有一个类型是“%”,但枚举不支持%,所以我想要一个默认值来解决它

\n

Ami*_*rsh 7

对于持有对 an 的引用enum而不设置值的人来说,默认值是null(在类字段的情况下自动设置,或者由用户显式设置)。

\n\n

不幸的是,您无法按原样覆盖valueOf您自己的方法。enumstatic

\n\n

但您仍然可以创建您的方法:

\n\n
public enum PartsOfSpeech2 {\n\n    n("noun"),\n    wp("\xe6\xa0\x87\xe7\x82\xb9"),\n    a("adjective"),\n    d("conjunction");\n\n    private String value;\n\n    PartsOfSpeech2(String value) {\n        this.value = value;\n    }\n\n    // declare your defaults with constant values\n    private final static PartsOfSpeech2 defaultValue = n;\n    private final static String defaultString = "%";\n\n    // `of` as a substitute for `valueOf` handling the default value\n    public static PartsOfSpeech2 of(String value) {\n        if(value.equals(defaultString)) return defaultValue;\n        return PartsOfSpeech2.valueOf(value);\n    }\n\n    // `defaultOr` for handling default value for null\n    public static PartsOfSpeech2 defaultOr(PartsOfSpeech2 value) {\n        return value != null ? value : defaultValue;\n    }\n\n    @Override\n    public String toString() { return value; }\n\n}\n
Run Code Online (Sandbox Code Playgroud)\n