Skip to content

Instantly share code, notes, and snippets.

@msakamoto-sf
Last active December 20, 2015 18:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save msakamoto-sf/6175058 to your computer and use it in GitHub Desktop.
Save msakamoto-sf/6175058 to your computer and use it in GitHub Desktop.
Groovy and enum demo. Groovy 1.8.9 doesn't suport enum's abstract method, but static initializer and metaClass makes nealy likely enable it. This is a work arround for http://jira.codehaus.org/browse/GROOVY-4641
// tested on Groovy 1.8.9.
enum GreetEnum {
MORNING("Good Morning"),
AFTERNOON("Good Afternoon"),
EVENING("Good Evening");
static {
MORNING.metaClass.greeting = { String you ->
return delegate.emphasize() + " " + you + ", I'm sleeping..."
}
AFTERNOON.metaClass.greeting = { String you ->
return delegate.greet + " " + you + ", let's coffee break!"
}
}
String greet
GreetEnum(String _greet) {
this.greet = _greet
}
String greeting(String you) {
throw new UnsupportedOperationException()
}
String emphasize() {
return this.greet + "!!"
}
}
assert GreetEnum.MORNING.greeting("abc") == "Good Morning!! abc, I'm sleeping..."
assert GreetEnum.AFTERNOON.greeting("abc") == "Good Afternoon abc, let's coffee break!"
//Caught: java.lang.UnsupportedOperationException
//assert GreetEnum.EVENING.greeting("abc") == "Good Evening abc"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment