Andy Andy - 5 days ago 5
Groovy Question

Groovy: Add references to methods in a property to a parent object

Say I have a class like this:

class Foo {
def doFoo() {
println "foo"
}
}


And another like this:

class Bar {
def doBar() {
println "bar"
}
}


And one more that looks like this:

class Baz {
Foo foo = new Foo()
Bar bar = new Bar()
}


With that example, what would it take to be able to use it like this:

Baz baz = new Baz()
baz.doFoo()
baz.doBar()


where the
doFoo
and
doBar
method calls simply delegate to the defined versions in their respective objects? Is there a way to do this with some kind of metaprogramming, or am I stuck defining each method individually as a wrapper?

Answer

@Delegate is what you need:

class Foo {
  def doFoo() {
    println "foo"
  }
}

class Bar {
  def doBar() {
    println "bar"
  }
}

class Baz {
  @Delegate
  Foo foo = new Foo()
  @Delegate
  Bar bar = new Bar()
}

Baz baz = new Baz()
baz.doFoo()
baz.doBar()