Conveniently map between enum and int / String

前端 未结 18 1826
陌清茗
陌清茗 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:26

    Really great question :-) I used solution similar to Mr.Ferguson`s sometime ago. Our decompiled enum looks like this:

    final class BonusType extends Enum
    {
    
        private BonusType(String s, int i, int id)
        {
            super(s, i);
            this.id = id;
        }
    
        public static BonusType[] values()
        {
            BonusType abonustype[];
            int i;
            BonusType abonustype1[];
            System.arraycopy(abonustype = ENUM$VALUES, 0, abonustype1 = new BonusType[i = abonustype.length], 0, i);
            return abonustype1;
        }
    
        public static BonusType valueOf(String s)
        {
            return (BonusType)Enum.valueOf(BonusType, s);
        }
    
        public static final BonusType MONTHLY;
        public static final BonusType YEARLY;
        public static final BonusType ONE_OFF;
        public final int id;
        private static final BonusType ENUM$VALUES[];
    
        static 
        {
            MONTHLY = new BonusType("MONTHLY", 0, 1);
            YEARLY = new BonusType("YEARLY", 1, 2);
            ONE_OFF = new BonusType("ONE_OFF", 2, 3);
            ENUM$VALUES = (new BonusType[] {
                MONTHLY, YEARLY, ONE_OFF
            });
        }
    }
    

    Seeing this is apparent why ordinal() is unstable. It is the i in super(s, i);. I'm also pessimistic that you can think of a more elegant solution than these you already enumerated. After all enums are classes as any final classes.

提交回复
热议问题