Java 枚举模版

92 阅读1分钟

项目中使用枚举,为了方便,编辑了模版,每次都能自动生成这些轮子:

1

2

#if (${PACKAGE_NAME} != "")package ${PACKAGE_NAME};#end

import java.util.HashMap;

#if (${IMPORT_BLOCK} != "")${IMPORT_BLOCK}
#end
#parse("File Header.java")

#if (${VISIBILITY} == "PUBLIC")public #end enum ${NAME} #if (${INTERFACES} != "")implements ${INTERFACES} #end {

    ONE(1, "one"),
    TWO(2, "two"),
    ;

    private Integer value;

    private String desc;


    ${NAME}(Integer value, String desc) {
        this.value = value;
        this.desc = desc;
    }

    public String getDesc() {
        return desc;
    }

    public void setDesc(String desc) {
        this.desc = desc;
    }

    public Integer getValue() {
        return value;
    }

    public void setValue(Integer value) {
        this.value = value;
    }


    public static Integer getValueByDesc(String desc){
        for (${NAME} enumItem : ${NAME}.values()) {
            if(enumItem.getDesc().equals(desc)){
                return enumItem.getValue();
            }
        }
        return -1;
    }

    public static String getDescByValue(Integer value){
        for (${NAME} enumItem : ${NAME}.values()) {
            if(enumItem.getValue().equals(value)){
                return enumItem.getDesc();
            }
        }
        return "";
    }

    public static HashMap<Integer, String> getMapData() {
        HashMap<Integer, String> map = new HashMap<>();
        for (${NAME} enumItem : ${NAME}.values()) {
            map.put(enumItem.getValue(), enumItem.getDesc());
        }
        return map;
    }
}