Java枚举类可以设置默认值

时间:2020-01-06 07:52:19

标签: java enums

Mycode是

public enum PartsOfSpeech2 {

    n("noun"),
    wp("标点"),
    a("adjective"),
    d("conjunction"),
    ...;

我想要的

public enum PartsOfSpeech2 {

    n("noun"),
    wp("标点"),
    a("adjective"),
    d("conjunction"),
    %("noun");

我可以拥有一个默认值吗,可以将其设置为默认值吗? 因为我的类型是“%”,但是枚举不支持%,所以我想要一个默认值来解决它

3 个答案:

答案 0 :(得分:0)

持有对enum的引用但未设置值的默认设置为null(在类字段的情况下自动生成,或由用户明确设置)。

很遗憾,您无法为自己的valueOf覆盖方法enum,因为它是static

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

public enum PartsOfSpeech2 {

    n("noun"),
    wp("标点"),
    a("adjective"),
    d("conjunction");

    private String value;

    PartsOfSpeech2(String value) {
        this.value = value;
    }

    // declare your defaults with constant values
    private final static PartsOfSpeech2 defaultValue = n;
    private final static String defaultString = "%";

    // `of` as a substitute for `valueOf` handling the default value
    public static PartsOfSpeech2 of(String value) {
        if(value.equals(defaultString)) return defaultValue;
        return PartsOfSpeech2.valueOf(value);
    }

    // `defaultOr` for handling default value for null
    public static PartsOfSpeech2 defaultOr(PartsOfSpeech2 value) {
        return value != null ? value : defaultValue;
    }

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

}

答案 1 :(得分:0)

来自JLS 8.9. Enums

枚举类型除了由其枚举常量定义的实例外,没有其他实例。尝试显式实例化枚举类型(第15.9.1节)是一个编译时错误。

因此您不能有任何采用默认值的实例。

您可以创建默认常量,并在某些条件下使用它。

public enum PartsOfSpeech2 {
  ....
  DEFAULT("DEFAULT");
}

并使用条件检查您的字符串是否具有常量,例如Ex "%"是否具有枚举。如果不使用默认值:

PartsOfSpeech2 result = PartsOfSpeech2.valueOf("%"); //Your String EX: %
PartsOfSpeech2 resultNew =  result==null?PartsOfSpeech2.DEFAULT: result;

答案 2 :(得分:0)

我解决的方法如下

public enum YourEnum{

ENUM1("stringToMatchWith"),
ENUM2("stringToMatchWith2"),
DEFAULTENUM("Default");

public final String label;

YourEnum(String label) {
    this.label = label;
}
public static YourEnum resolveYourEnum(String stringToMatch) {
    return Arrays.stream(YourEnum.values()).filter(aEnum -> aEnum.label.equals(stringToMatch)).findFirst().orElse(YourEnum.DEFAULTENUM);
}

这样你就可以做 YourEnum.resolveYourEnum("aString") 并返回指定的枚举或我们设置的默认值

相关问题