• support@answerspoint.com

Convert a String to an enum in Java

2143

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 "A" which would be Blah.A. How would it be possible to do this?

Is the Enum.valueOf() the method I need? If so, how would I use this?

  • Java

  • asked 9 years ago
  • B Butts

2Answer


0

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

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.

  • answered 8 years ago
  • Sunny Solu

0

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) {
    if (text != null) {
      for (Blah b : Blah.values()) {
        if (text.equalsIgnoreCase(b.text)) {
          return b;
        }
      }
    }
    return null;
  }
}
  • answered 8 years ago
  • G John

Your Answer

    Facebook Share        
       
  • asked 9 years ago
  • viewed 2143 times
  • active 9 years ago

Best Rated Questions