How to convert string result of enum with overridden toString() back to enum?

后端 未结 6 900
醉话见心
醉话见心 2021-01-31 10:30

Given the following java enum:

public enum AgeRange {

   A18TO23 {
        public String toString() {        
            return \"18 - 23\";
        }
    },
          


        
6条回答
  •  萌比男神i
    2021-01-31 10:51

    for (AgeRange ar: EnumSet.allOf(AgeRange)) {
        if (ar.toString().equals(inString)) {
             myAnswer = ar;
             break;
        }
    }
    

    Or something like that? Just typed in, haven't run through a compiler. Forgive (comment on) typos...

    Or use logic like this to build a map once. Avoid iteration at runtime. Good idea, Jon.

提交回复
热议问题