Groovy的:在一个属性添加引用方法父对象

问题描述:

说我有一个这样的类:Groovy的:在一个属性添加引用方法父对象

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

而另一个是这样的:

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

而且多了一个看起来像这样:

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

有了这个例子中,那会是什么才能成为能够使用这样的:

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

其中doFoodoBar方法调用只是委托给各自对象中的已定义版本?有没有办法做到这一点与某种元编程,或者我坚持每个方法单独定义为包装?

+0

发现了另一个职位,进入更详细的关于AST转换及性状:http://stackoverflow.com/a/23124968/493807 – Andy

@Delegate是你所需要的:

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() 
+0

就在发现自己。仍在学习Groovy并且每天都更加热爱它! – Andy

+0

@安迪,是的,这是非常好的语言。 – Opal