Convert String to equivalent Enum value

后端 未结 4 2051
一向
一向 2020-12-12 20:18

Is it possible for me to convert a String to an equivalent value in an Enumeration, using Java.

I can of course do this with a large

4条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-12 20:40

    I might've over-engineered my own solution without realizing that Type.valueOf("enum string") actually existed.

    I guess it gives more granular control but I'm not sure it's really necessary.

    public enum Type {
        DEBIT,
        CREDIT;
    
        public static Map typeMapping = Maps.newHashMap();
        static {
            typeMapping.put(DEBIT.name(), DEBIT);
            typeMapping.put(CREDIT.name(), CREDIT);
        }
    
        public static Type getType(String typeName) {
            if (typeMapping.get(typeName) == null) {
                throw new RuntimeException(String.format("There is no Type mapping with name (%s)"));
            }
            return typeMapping.get(typeName);
        }
    }
    

    I guess you're exchanging IllegalArgumentException for RuntimeException (or whatever exception you wish to throw) which could potentially clean up code.

提交回复
热议问题