Groovy: Few ways to convert string into enum
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
Thanks Burt, I have updated the post as per your suggestion.
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.