9

假设我有这个枚举:

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")

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

4

4 回答 4

27

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

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

然后,您可以调用:

MyEnum.valueOfName( "Australia/Adelaide" )
于 2013-09-16T08:34:44.347 回答
9

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]
于 2014-12-18T00:34:49.857 回答
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
于 2014-07-06T03:39:04.723 回答
-1
assert AccountType.CHECKING == "CHECKING" as AccountType
于 2015-04-12T03:06:27.390 回答