欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

枚举类的简单应用

程序员文章站 2022-03-04 14:23:39
...

java 枚举类简单定义与应用

  1. 什么是枚举类:(举个栗子????)
    // 声明枚举时必须使用 enum 关键字
    public enum ResTypeEnum implements ResTypeImpl {
    
    /**
    * 艺术品
    */
    YP(1, "艺术品", "ADBA_RES_AW", "aw"),
    YT(2, "艺术品图片", "ADBA_RES_AWIMG", "awimg"),
    RW(3, "艺术人物", "ADBA_RES_GA", "ga"),
    TJ(4, "图书集", "ADBA_RES_SET", "book-set"),
    TS(5, "图书", "ADBA_RES_BOOK", "book"),
    KA(6, "刊", "ADBA_RES_JOURNAL", "journal"),
    QK(7, "期", "ADBA_RES_PERIODICAL", "periodical"),
    PJ(8, "拍卖机构", "ADBA_RES_AC", "ac"),
    CJ(9, "出版机构", "ADBA_RES_EC", "ec"),
    HJ(10, "画廊机构", "ADBA_RES_GC", "gc"),
    WJ(11, "文博机构", "ADBA_RES_CEC", "cec"),
    QJ(12, "其他机构", "ADBA_RES_ORG", "org"),
    PM(13, "拍卖会", "ADBA_RES_AUCTION", "auction"),
    PZ(14, "拍卖专场", "ADBA_RES_ASA", "asa"),
    ZL(15, "展览会", "ADBA_RES_EXHIBITION", "exhibition"),
    QT(16, "其他活动", "ADBA_RES_ACTIVITY", "activity"),
    WX(17, "文献", "ADBA_RES_INFO", "info"),
    SP(18, "视频", "ADBA_RES_VIDEO", "video"),
    ZP(19, "非艺术品图片", "ADBA_RES_IMG", "img");
    
    
    private Long resId;
    private String name;
    private String tableName;
    private String abbreviation;
    
    ResTypeEnum(long resId, String name, String tableName, String abbreviation) {
     this.resId = resId;
     this.name = name;
     this.tableName = tableName;
     this.abbreviation = abbreviation;
    }
    
    
    @Override
    public Long getResId() {
     return resId;
    }
    
    
    @Override
    public String getName() {
     return name;
    }
    
    @Override
    public String getTableName() {
     return tableName;
    }
    
    @Override
    public String getAbbreviation() {
     return abbreviation;
    }
    

`
可以看出,枚举类相对普通类只是定义类的关键字由原来的的class ,变为enum。而且多了一段枚举值。

  1. 枚举类是使用 与其他class类一样,可以直接调用
  public static void main(String[] args) {
        ResTypeEnum cj = ResTypeEnum.CJ;
        ResTypeEnum.getResIdByTableName("ADS");
    }
  1. 定义枚举中常用的方法(根据key获取 value、根据value获取key)
		  /**
     *  根据枚举的value 获取枚举的key
     * @param tableName 枚举的value
     * @return  返回枚举的 code 失败返回 null
     */
    public static Long getResIdByTableName(String tableName){
        ResTypeEnum [] resTypeEnums = values(); //获取枚举的是所有值存入数组
        for (ResTypeEnum resTypeEnum : resTypeEnums) {
            if (resTypeEnum.tableName.equals(tableName.toUpperCase(Locale.ROOT))){
                return resTypeEnum.resId;
            }
        }
        return null;
    }

    /**
     *  根据枚举的code 获取枚举的value
     * @param resId 枚举的code
     * @return 返回枚举的value  失败返回 null
     */
    public static String getTableNameByResId(Long resId){
        ResTypeEnum [] resTypeEnums = values();//获取枚举的是所有值存入数组
        for (ResTypeEnum resTypeEnum : resTypeEnums) {
            if (resTypeEnum.resId.equals(resId)){
                return resTypeEnum.tableName;
            }
        }
        return null;
    }

相关标签: 学习,复习