Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Grails String to enum?

Tags:

grails

groovy

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?

like image 861
goo_xara Avatar asked Sep 16 '13 08:09

goo_xara


1 Answers

Add the following to your enum:

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

Then, you can call:

MyEnum.valueOfName( "Australia/Adelaide" )
like image 88
tim_yates Avatar answered Nov 13 '22 15:11

tim_yates