Skip to content

Instantly share code, notes, and snippets.

@melix
Created September 12, 2012 10:30
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save melix/3705806 to your computer and use it in GitHub Desktop.
Save melix/3705806 to your computer and use it in GitHub Desktop.
Groovy dynamic delegate
class Foo {}
class Bar { void baz() { println 'baz' } }
def delegate = new Bar()
// attention, toutes les instances de Foo seront redirigées vers le même delegate. Sinon, utiliser foo.metaClass par instance
Foo.metaClass.invokeMethod = { name, args -> delegate."$name"(*args) }
new Foo().baz()
// Autre solution, plus propre, avec @Delegate
class Foo {
@Delegate Bar bar = new Bar()
}
class Bar { void baz() { println 'baz' } }
new Foo().baz()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment