Conveniently map between enum and int / String

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

    A very clean usage example of reverse Enum

    Step 1 Define an interface EnumConverter

    public interface EnumConverter  & EnumConverter> {
        public String convert();
        E convert(String pKey);
    }
    

    Step 2

    Create a class name ReverseEnumMap

    import java.util.HashMap;
    import java.util.Map;
    
    public class ReverseEnumMap & EnumConverter> {
        private Map map = new HashMap();
    
        public ReverseEnumMap(Class valueType) {
            for (V v : valueType.getEnumConstants()) {
                map.put(v.convert(), v);
            }
        }
    
        public V get(String pKey) {
            return map.get(pKey);
        }
    }
    

    Step 3

    Go to you Enum class and implement it with EnumConverter and of course override interface methods. You also need to initialize a static ReverseEnumMap.

    public enum ContentType implements EnumConverter {
        VIDEO("Video"), GAME("Game"), TEST("Test"), IMAGE("Image");
    
        private static ReverseEnumMap map = new ReverseEnumMap(ContentType.class);
    
        private final String mName;
    
        ContentType(String pName) {
            this.mName = pName;
        }
    
        String value() {
            return this.mName;
        }
    
        @Override
        public String convert() {
            return this.mName;
        }
    
        @Override
        public ContentType convert(String pKey) {
            return map.get(pKey);
        }
    }
    

    Step 4

    Now create a Communication class file and call it's new method to convert an Enum to String and String to Enum. I have just put main method for explanation purpose.

    public class Communication & EnumConverter> {
        private final E enumSample;
    
        public Communication(E enumSample) {
            this.enumSample = enumSample;
        }
    
        public String resolveEnumToStringValue(E e) {
            return e.convert();
        }
    
        public E resolveStringEnumConstant(String pName) {
            return enumSample.convert(pName);
        }
    
    //Should not put main method here... just for explanation purpose. 
        public static void main(String... are) {
            Communication comm = new Communication(ContentType.GAME);
            comm.resolveEnumToStringValue(ContentType.GAME); //return Game
            comm.resolveStringEnumConstant("Game"); //return GAME (Enum)
        }
    }
    

    Click for for complete explanation

提交回复
热议问题