2

如何创建一个类型,它是 aMarkupBuilder但具有用 a 初始化的默认构造函数StringWriter并覆盖以toString()调用?toString()StringWriter

思路如下,当然不允许在调用超级构造函数之前初始化实例变量:

class StringWriterMarkupBuilder extends MarkupBuilder {
    final def sw = new StringWriter()
    StringWriterMarkupBuilder() {
        super(sw)
    }

    @Override String toString() {
        sw.toString()
    }
}
4

2 回答 2

2

抱歉,我终于通过深入研究 MarkupBuilder 的 Groovy 源代码找到了解决方案!:

class StringWriterMarkupBuilder extends MarkupBuilder {
    StringWriterMarkupBuilder() {
        //MarkupBuilder.this(new IndentPrinter(new PrintWriter(writer)))
        super(new StringWriter()) 
    }

    @Override String toString() {
        //IndentPrinter.PrintWriter.StringWriter
        return super.getPrinter().out.out.toString()
    }
}
于 2012-05-19T13:40:37.827 回答
1

You could also do this with the metaClass like so:

import groovy.xml.MarkupBuilder

MarkupBuilder createSWMB() {
  new StringWriter().with { sw ->
    new MarkupBuilder( sw ).with { mb ->
      mb.metaClass.toString = { -> sw.toString() }
      mb
    } 
  }
}

MarkupBuilder mb = createSWMB()
mb.root {
  names {
    name( first:'tim', second:'yates' )
  }
}
println mb.toString()
于 2012-05-21T09:01:00.817 回答