Skip to content
Advertisement

Can Java enum class set default value

Mycode is

public enum PartsOfSpeech2 {

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

which I want

public enum PartsOfSpeech2 {

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

can I hava a default value which is not in it, can it be set as a default value? because I have a type is “%”, but enum is not support %, so I want a default value to solve it

Advertisement

Answer

The default for one who holds a reference to an enum without setting a value would be null (either automatically in case of a class field, or set by the user explicitly).

Unfortunately you cannot override the method valueOf for your own enum, as it is static.

But you can still create your methods:

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; }

}
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement