Conveniently map between enum and int / String

前端 未结 18 1868
陌清茗
陌清茗 2020-11-28 01:07

When working with variables/parameters that can only take a finite number of values, I try to always use Java\'s enum, as in

public enum BonusT         


        
18条回答
  •  天命终不由人
    2020-11-28 01:13

    enum → int

    yourEnum.ordinal()
    

    int → enum

    EnumType.values()[someInt]
    

    String → enum

    EnumType.valueOf(yourString)
    

    enum → String

    yourEnum.name()
    

    A side-note:
    As you correctly point out, the ordinal() may be "unstable" from version to version. This is the exact reason why I always store constants as strings in my databases. (Actually, when using MySql, I store them as MySql enums!)

提交回复
热议问题