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

前端 未结 27 2263
旧巷少年郎
旧巷少年郎 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: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");
    

提交回复
热议问题