Last active
August 29, 2015 14:08
-
-
Save melix/825ed166f63263068efa to your computer and use it in GitHub Desktop.
DelegatesTo any type in Groovy 2.4+
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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