假设我有这个枚举:
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
}
}
Run Code Online (Sandbox Code Playgroud)
有没有办法让我使用其值/名称获取枚举?现在,我正在尝试这样做,但它不起作用:
MyEnum.valueOf("Australia/Sydney")
Run Code Online (Sandbox Code Playgroud)
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?
tim*_*tes 26
Add the following to your enum:
static MyEnum valueOfName( String name ) {
values().find { it.name == name }
}
Run Code Online (Sandbox Code Playgroud)
Then, you can call:
MyEnum.valueOfName( "Australia/Adelaide" )
Run Code Online (Sandbox Code Playgroud)
为了完整性添加到以前的答案,这里有其他选项,结合了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]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10349 次 |
| 最近记录: |