or

Convert String to Enum

Last month we were coding some Groovy stuff and we needed to use Enum equivalents of couple Strings. We had couple dynamic Strings coming from off-shore developers, which defines the type of the entity. In our system, those types were represented by Enums. Anyways, basically we had to resolve the Enums from given Strings. After a little reading, we came up with following solution:


enum Colors {
  BLUE,
  WHITE
}

// ..

Colors blue = Enum.valueOf(Colors.class, "BLUE");

I thought I should post a blog entry about this :)



3 Responses

  1. BSR

    Thanks!!

    April 25, 2010, 7:06 AM
  2. Marty

    If you know this is gonna be “Color” why not using

    Colors blue = Colors.valueOf(”BLUE”);

    ?

    April 28, 2010, 6:43 AM
  3. bob

    Enum.valueOf(Colors.class, “BLUE”) should be written as Colors.valueOf(”BLUE”)

    December 30, 2010, 3:39 AM

Leave a Reply

Name (required)
Mail (required)
Website