实现methodMissing()时,Groovy停止工作

时间:2013-09-05 05:50:00

标签: groovy

import groovy.xml.MarkupBuilder
class Foo {
    Foo() {}
    String boo() {
        def writer = new StringWriter()
        def xml = new MarkupBuilder(writer)
        xml.records() {
            car(name:'HSV Maloo', make:'Holden', year:2006) {
                country('Australia')
                record(type:'speed', 'Production Pickup Truck with speed of 271kph')
            }
        }
        println writer
    }
    def methodMissing(String methodName, args) {
        println "Get called"
    }
}

Foo a = new Foo()
a.boo()

结果:

Get called
<records />

未实施methodMissing(),结果:

<records>
  <car name='HSV Maloo' make='Holden' year='2006'>
    <country>Australia</country>
    <record type='speed'>Production Pickup Truck with speed of 271kph</record>
  </car>
</records>

我现在正在摸不着头脑,我在这里想念的是什么?

1 个答案:

答案 0 :(得分:1)

问题在于,当boo()被调用时,会创建MarkupBuilder并最终点击:

        car(name:'HSV Maloo', make:'Holden', year:2006) {

这将检查您的类中的car方法,如果找不到,则会在closure(MarkupBuilder)的委托中检查一个方法。 MarkupBuilder捕获了这个,并生成一个xml节点。

但是,您已定义methodMissing,因此当它检查您的类的car方法时,它会找到一个并使用它而不做任何事情

要解决此问题,您可以通过致电xml.car()xml.country()等来明确要求使用MarkupBuilder:

String boo() {
    def writer = new StringWriter()
    def xml = new MarkupBuilder(writer)
    xml.records() {
        xml.car(name:'HSV Maloo', make:'Holden', year:2006) {
            xml.country('Australia')
            xml.record(type:'speed', 'Production Pickup Truck with speed of 271kph')
        }
    }
    println writer
}