如何创建一个MarkupBuilder
但具有默认构造函数的类型,该构造函数使用StringWriter
初始化并覆盖toString()
以调用toString()
StringWriter
1}}?
这个想法如下,但当然不允许在超级构造函数调用之前初始化实例变量:
class StringWriterMarkupBuilder extends MarkupBuilder {
final def sw = new StringWriter()
StringWriterMarkupBuilder() {
super(sw)
}
@Override String toString() {
sw.toString()
}
}
答案 0 :(得分: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()
}
}
答案 1 :(得分:1)
你也可以使用metaClass
这样做:
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()