Java字符串转枚举

import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

public enum SeasonEnum {

    SPRING("春"),

    SUMMER("夏"),

    AUTUMN("秋"),

    WINTER("冬");

    private static final Map<String, SeasonEnum> MAP = new HashMap<>();

    static {

        for (SeasonEnum season : values()) {
            MAP.put(season.name, season);
        }
    }

    private final String name;

    private SeasonEnum(String name) {

        this.name = name;
    }

    public static SeasonEnum valueOfName(String name) {

        return MAP.get(name);
    }

    public String toLocale() {

        if (Locale.CHINA.equals(Locale.getDefault())) {
            return name;
        }
        return toString();
    }

    public static void main(String[] args) {

        // 如果转换不成功,抛出 java.lang.IllegalArgumentException
        SeasonEnum spring = SeasonEnum.valueOf("SPRING");
        System.out.println(spring);

        SeasonEnum summer = SeasonEnum.valueOfName("夏");
        System.out.println(summer);

        System.out.println(SeasonEnum.AUTUMN.toLocale());
    }
}

原文:https://www.cnblogs.com/jiangbo44/p/12801462.html

posted @ 2021-02-26 16:14  lovleo  阅读(2131)  评论(0编辑  收藏  举报