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?
Add the following to your enum:
static MyEnum valueOfName( String name ) {
values().find { it.name == name }
}
Then, you can call:
MyEnum.valueOfName( "Australia/Adelaide" )
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With