goo_xara
goo_xara

Reputation: 103

Grails String to enum?

Suppose I have this enum:

public enum MyEnum {
    AUSTRALIA_SYDNEY ("Australia/Sydney"),
    AUSTRALIA_ADELAIDE ("Australia/Adelaide"),

    private String name

    private Timezone(String name){
        this.name = name
    }

    public String value() {
        name
    }

    String toString() {
        name
    }
}

Is there a way for me to get the enum using its value/name? Right now, I'm trying to do this, but it doesn't work:

MyEnum.valueOf("Australia/Sydney")

What I'm getting from the DB is a string (in this case: "Australia/Sydney"), and not the value, and unfortunately, I can't just alter the type it returns because its an old system and I'm just connecting to this DB that is shared by multiple apps. Anyway around this?

Upvotes: 9

Views: 12395

Answers (4)

tsunllly
tsunllly

Reputation: 1668

assert AccountType.CHECKING == "CHECKING" as AccountType

Upvotes: -1

dbrin
dbrin

Reputation: 15673

For completeness to add to previous answers here are additional options which combine the post referenced from Mr. Haki. This answer is taken from Amit Jain's blog post: http://www.intelligrape.com/blog/groovy-few-ways-to-convert-string-into-enum/

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]

Upvotes: 9

Hussain Fakhruddin
Hussain Fakhruddin

Reputation: 3272

With reference to blog http://mrhaki.blogspot.ae/2010/12/groovy-goodness-transform-string-into.html there are multiple ways to convert String to Enum.

enum Compass {
    NORTH, EAST, SOUTH, WEST
}

// Coersion with as keyword.
def north = 'NORTH' as Compass
assert north == Compass.NORTH

// Coersion by type.
Compass south = 'south'.toUpperCase()
assert south == Compass.SOUTH

def result = ['EA', 'WE'].collect {
    // Coersion of GString to Enum.
    "${it}ST" as Compass
}
assert result[0] == Compass.EAST
assert result[1] == Compass.WEST

Upvotes: 4

tim_yates
tim_yates

Reputation: 171194

Add the following to your enum:

static MyEnum valueOfName( String name ) {
    values().find { it.name == name }
}

Then, you can call:

MyEnum.valueOfName( "Australia/Adelaide" )

Upvotes: 27

Related Questions