Skip to content

Instantly share code, notes, and snippets.

@melix
Last active August 29, 2015 14:08
Show Gist options
  • Save melix/825ed166f63263068efa to your computer and use it in GitHub Desktop.
Save melix/825ed166f63263068efa to your computer and use it in GitHub Desktop.
DelegatesTo any type in Groovy 2.4+
trait Configurable<ConfigObject> {
ConfigObject configObject
void configure(Closure<Void> configSpec) {
configSpec.resolveStrategy = Closure.DELEGATE_FIRST
configSpec.delegate = configObject
configSpec()
}
}
public <T,U extends Configurable<T>> U configure(Class<U> clazz, @DelegatesTo(type="T") Closure configSpec) {
Configurable<T> obj = (Configurable<T>) clazz.newInstance()
obj.configure(configSpec)
obj
}
class Module implements Configurable<ModuleConfig> {
String value
Module(){
configObject = new ModuleConfig()
}
@Override
void configure(Closure<Void> configSpec) {
Configurable.super.configure(configSpec)
value = "${configObject.name}-${configObject.version}"
}
}
class ModuleConfig {
String name
String version
}
@CompileStatic
void doTest() {
def module = configure(Module) {
name = 'test'
version = '1.0'
}
assert module.value == 'test-1.0'
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment