Conveniently map between enum and int / String

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

    Just because the accepted answer is not self contained:

    Support code:

    public interface EnumWithCode & EnumWithCode> {
    
        public Integer getCode();
    
        E fromCode(Integer code);
    }
    
    
    public class EnumWithCodeMap & EnumWithCode> {
    
        private final HashMap _map = new HashMap();
    
        public EnumWithCodeMap(Class valueType) {
            for( V v : valueType.getEnumConstants() )
                _map.put(v.getCode(), v);
        }
    
        public V get(Integer num) {
            return _map.get(num);
        }
    }
    

    Example of use:

    public enum State implements EnumWithCode {
        NOT_STARTED(0), STARTED(1), ENDED(2);
    
        private static final EnumWithCodeMap map = new EnumWithCodeMap(
                State.class);
    
        private final int code;
    
        private State(int code) {
            this.code = code;
        }
    
        @Override
        public Integer getCode() {
            return code;
        }
    
        @Override
        public State fromCode(Integer code) {
            return map.get(code);
        }
    
    }
    

提交回复
热议问题