How to get an enum value from a string value in Java?

前端 未结 27 2192
旧巷少年郎
旧巷少年郎 2020-11-21 10:53

Say I have an enum which is just

public enum Blah {
    A, B, C, D
}

and I would like to find the enum value of a string, for example

27条回答
  •  说谎
    说谎 (楼主)
    2020-11-21 11:56

    java.lang.Enum defines several useful methods, which is available to all enumeration type in Java:

    • You can use name() method to get name of any Enum constants. String literal used to write enum constants is their name.
    • Similarly values() method can be used to get an array of all Enum constants from an Enum type.
    • And for the asked question, you can use valueOf() method to convert any String to Enum constant in Java, as shown below.
    public class EnumDemo06 {
        public static void main(String args[]) {
            Gender fromString = Gender.valueOf("MALE");
            System.out.println("Gender.MALE.name() : " + fromString.name());
        }
    
        private enum Gender {
            MALE, FEMALE;
        }
    }
    
    Output:
    Gender.MALE.name() : MALE
    

    In this code snippet, valueOf() method returns an Enum constant Gender.MALE, calling name on that returns "MALE".

提交回复
热议问题