JavaDevNotes.com

Groovy Convert String to Enum

Enum is a very convenient way of representing a group of information that is fairly static. For example, Sex, Marital Status, and such can be represented by Enum. Enum is great way to do things instead of constant because it is more intuitive and easy to work with. However, when we store Enums to database or transfer it as a message to another process, we convert it into String. The question now is, how do we turn back a String to Enum? Below are some examples that converts a String to Enum in Groovy. And we know that Groovy has beautiful magic to do this.

Using as keyword

Because we are in Groovy world, we can count that things is much easier, concise, and intuitive. Below is the most basic way to solve this using the as keyword.
enum MaritalStatus {
	SINGLE, MARRIED, WIDOW
	MaritalStatus() {
	}
}
String myString = 'MARRIED'
MaritalStatus enumValue = myString as MaritalStatus
println enumValue
The above code shows that we just use as keyword after the String followed by the enum class name. Groovy is intelligent enough to guess what we want to do here. And so the output of the above code is this:
MARRIED

Using Coercion

And since this is Groovy, the as keyword seems too hard or an overkill. So the developers of Groovy designed a solution such that we just assign the string value to a variable of type enum. No more keyword as Groovy is intelligent enough to solve this through implicit coercion. Here is an example:
enum MaritalStatus {
	SINGLE, MARRIED, WIDOW
	MaritalStatus() {
	}
}
String myString = 'WIDOW'
MaritalStatus enumValue = myString
println enumValue

We just assign the String 'WIDOW' straight to the enum variable and it is done and over with. The output is below:

WIDOW

Pitfall

Regardless of what approach we do, the String should correspond to one of the declared enum values. Otherwise, Groovy will throw an exception. For example:
enum MaritalStatus {
    SINGLE, MARRIED, WIDOW
    MaritalStatus() {
    }
}
String myString = 'Male'
MaritalStatus enumValue = myString as MaritalStatus
println enumValue

Will result to

Caught: java.lang.IllegalArgumentException: No enum constant groovy.MaritalStatus.Male
java.lang.IllegalArgumentException: No enum constant groovy.MaritalStatus.Male

And this is a sample invalid code using coercion.
enum MaritalStatus {
    SINGLE, MARRIED, WIDOW
    MaritalStatus() {
    }
}
String myString = 'Female'
MaritalStatus enumValue = myString 
println enumValue
That will yield the error:
Caught: java.lang.IllegalArgumentException: No enum constant groovy.MaritalStatus.Female
java.lang.IllegalArgumentException: No enum constant groovy.MaritalStatus.Female