Convert String to equivalent Enum value

后端 未结 4 2034
一向
一向 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:30

    Assuming you use Java 5 enums (which is not so certain since you mention old Enumeration class), you can use the valueOf method of java.lang.Enum subclass:

    MyEnum e = MyEnum.valueOf("ONE_OF_CONSTANTS");
    
    0 讨论(0)
  • 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<String, Type> 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.

    0 讨论(0)
  • 2020-12-12 20:44

    Hope you realise, java.util.Enumeration is different from the Java 1.5 Enum types.

    You can simply use YourEnum.valueOf("String") to get the equivalent enum type.

    Thus if your enum is defined as so:

    public enum Day {
        SUNDAY, MONDAY, TUESDAY, WEDNESDAY, 
        THURSDAY, FRIDAY, SATURDAY
    }
    

    You could do this:

    String day = "SUNDAY";
    
    Day dayEnum = Day.valueOf(day);
    
    0 讨论(0)
  • 2020-12-12 20:53

    Use static method valueOf(String) defined for each enum.

    For example if you have enum MyEnum you can say MyEnum.valueOf("foo")

    0 讨论(0)
提交回复
热议问题