Grails字符串枚举?

时间:2013-09-16 08:32:02

标签: grails groovy

假设我有这个枚举:

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
    }
}

有没有办法让我使用其值/名称获取枚举? 现在,我正在尝试这样做,但它不起作用:

MyEnum.valueOf("Australia/Sydney")

我从数据库中得到的是一个字符串(在这种情况下:“澳大利亚/悉尼”),而不是价值,不幸的是,我不能只改变它返回的类型,因为它是旧的 系统,我只是连接到这个由多个应用程序共享的数据库。无论如何围绕这个?

4 个答案:

答案 0 :(得分:26)

将以下内容添加到枚举中:

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

然后,您可以致电:

MyEnum.valueOfName( "Australia/Adelaide" )

答案 1 :(得分:8)

为了完整性添加到以前的答案,这里有其他选项,结合了Haki先生引用的帖子。这个答案取自Amit Jain的博客文章: 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]

答案 2 :(得分:4)

参考博客http://mrhaki.blogspot.ae/2010/12/groovy-goodness-transform-string-into.html,有多种方法可以将String转换为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

答案 3 :(得分:-1)

assert AccountType.CHECKING == "CHECKING" as AccountType