How can I eliminate duplicated Enum code?

后端 未结 15 896
眼角桃花
眼角桃花 2020-12-24 13:40

I have a large number of Enums that implement this interface:

/**
 * Interface for an enumeration, each element of which can be uniquely identified by its co         


        
15条回答
  •  -上瘾入骨i
    2020-12-24 14:10

    Another solution would be not to put anything into the enum itself, and just provide a bi-directional map Enum <-> Code for each enum. You could e.g. use ImmutableBiMap from Google Collections for this.

    That way there no duplicate code at all.

    Example:

    public enum MYENUM{
      VAL1,VAL2,VAL3;
    }
    
    /** Map MYENUM to its ID */
    public static final ImmutableBiMap MYENUM_TO_ID = 
    new ImmutableBiMap.Builder().
    put(MYENUM.VAL1, 1).
    put(MYENUM.VAL2, 2).
    put(MYENUM.VAL3, 3).
    build();
    

提交回复
热议问题