Groovy: Few ways to convert string into enum

15 / Apr / 2011 by Amit Jain 2 comments

Many at times, we have a string which needs to be converted into Enum. I will be sharing few options as stated by Mr.Haki, Isa Goksu and in the last the one I discovered during the process. Lets say we have a Enum AccountType as given below :

[groovy]

enum AccountType {
CHECKING,
SAVING
}

assert AccountType.CHECKING == "CHECKING" as AccountType

assert AccountType.CHECKING == AccountType.valueOf("CHECKING")
def className = AccountType.class
assert AccountType.CHECKING == Enum.valueOf(className, "CHECKING")

assert AccountType.CHECKING == AccountType["CHECKING"]
String type = "CHECKING"
assert AccountType.CHECKING == AccountType[type]

[/groovy]

Cheers!
~~Amit Jain~~
amit@intelligrape.com
http://www.tothenew.com

FOUND THIS USEFUL? SHARE IT

comments (2)

  1. Burt Beckwith

    I would use Enum.valueOf(AccountType.class, “CHECKING”) only if I didn’t know the type of the enum class, e.g. if the class were passed as a parameter to a method. If you know it’s an AccountType you can just use the traditional AccountType.valueOf(‘Checking’) as pointed out in the comments of the post you referenced.

    Reply

Leave a Reply to Amit Jain Cancel reply

Your email address will not be published. Required fields are marked *