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

前端 未结 27 2184
旧巷少年郎
旧巷少年郎 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

    Another solution if the text is not the same to the enumeration value:

    public enum Blah {
        A("text1"),
        B("text2"),
        C("text3"),
        D("text4");
    
        private String text;
    
        Blah(String text) {
            this.text = text;
        }
    
        public String getText() {
            return this.text;
        }
    
        public static Blah fromString(String text) {
            for (Blah b : Blah.values()) {
                if (b.text.equalsIgnoreCase(text)) {
                    return b;
                }
            }
            return null;
        }
    }
    
    0 讨论(0)
  • 2020-11-21 11:56

    You should also be careful with your case. Let me explain: doing Blah.valueOf("A") works, but Blah.valueOf("a") will not work. Then again Blah.valueOf("a".toUpperCase(Locale.ENGLISH)) would work.

    edit
    Changed toUpperCase to toUpperCase(Locale.ENGLISH) based on tc. comment and the java docs

    edit2 On android you should use Locale.US, as sulai points out.

    0 讨论(0)
  • 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".

    0 讨论(0)
  • 2020-11-21 11:56

    Fastest way to get the name of enum is to create a map of enum text and value when the application start, and to get the name call the function Blah.getEnumName():

    public enum Blah {
        A("text1"),
        B("text2"),
        C("text3"),
        D("text4");
    
        private String text;
        private HashMap<String, String> map;
        Blah(String text) {
        this.text = text;
        }
    
        public String getText() {
          return this.text;
        }
    
        static{
          createMapOfTextAndName();
        }
    
        public static void createMapOfTextAndName() {
            map = new HashMap<String, String>();
            for (Blah b : Blah.values()) {
                 map.put(b.getText(),b.name());
            }
        }
        public static String getEnumName(String text) {
            return map.get(text.toLowerCase());
        } 
    }
    
    0 讨论(0)
  • 2020-11-21 11:57

    Yes, Blah.valueOf("A") will give you Blah.A.

    Note that the name must be an exact match, including case: Blah.valueOf("a") and Blah.valueOf("A ") both throw an IllegalArgumentException.

    The static methods valueOf() and values() are created at compile time and do not appear in source code. They do appear in Javadoc, though; for example, Dialog.ModalityType shows both methods.

    0 讨论(0)
  • 2020-11-21 11:58

    Enum is very useful, I have been using Enum a lot to add a description for some fields in different languages, as the following example:

    public enum Status {
    
        ACT(new String[] { "Accepted", "مقبول" }),
        REJ(new String[] { "Rejected", "مرفوض" }),
        PND(new String[] { "Pending", "في الانتظار" }),
        ERR(new String[] { "Error", "خطأ" }),
        SNT(new String[] { "Sent", "أرسلت" });
    
        private String[] status;
    
        public String getDescription(String lang) {
            return lang.equals("en") ? status[0] : status[1];
        }
    
        Status(String[] status) {
            this.status = status;
        }
    }
    

    And then you can retrieve the description dynamically based in the language code passed to getDescription(String lang) method, for example:

    String statusDescription = Status.valueOf("ACT").getDescription("en");
    
    0 讨论(0)
提交回复
热议问题