Groovy 生成器支持

ani*_*ish 1 dsl groovy closures

我如何使用 groovy builder 支持构建上述模式

emp = empFileFactory.root()
{
  emp(id: '3', value: '1')

  emp(id:'24')
  {
    emp(id: '1', value: '2')
    emp(id: '6', value: '7')
    emp(id: '7', value: '1')
  }

  emp(id: '25')
  {
    emp(id: '1', value: '1')
    emp(id: '6', value: '7')
  }

}
Run Code Online (Sandbox Code Playgroud)

我正在尝试在 groovy 中构建上述结构,有人可以解释我如何实现这一点

tim*_*tes 5

你可以做这样的事情(这没有错误处理,并且只为我不希望被调用的方法返回 null):

// First define our class to hold our created 'Emp' objects
@groovy.transform.Canonical
class Emp {
  String id
  String value
  List<Emp> children = []
}

class EmpBuilder extends BuilderSupport{
  def children = []
  protected void setParent(Object parent, Object child){
    parent.children << child
  }
  protected Object createNode(Object name){
    if( name == 'root' ) {
      this
    }
    else {
      null
    }
  }
  protected Object createNode(Object name, Object value){
    null
  }
  protected Object createNode(Object name, Map attributes){
    if( name == 'emp' ) {
      new Emp( attributes )
    }
    else {
      null
    }
  }
  protected Object createNode(Object name, Map attributes, Object value){
    null
  }
  protected void nodeCompleted(Object parent, Object node) {
  }
  Iterator iterator() { children.iterator() }
}
Run Code Online (Sandbox Code Playgroud)

然后,如果我们使用您所需的构建器代码调用它,如下所示:

b = new EmpBuilder().root() {
  emp(id: '3', value: '1')

  emp(id:'24') {
    emp(id: '1', value: '2')
    emp(id: '6', value: '7')
    emp(id: '7', value: '1')
  }

  emp(id: '25') {
    emp(id: '1', value: '1')
    emp(id: '6', value: '7')
  }
}
Run Code Online (Sandbox Code Playgroud)

我们可以像这样打印出“树”

b.each { println it }
Run Code Online (Sandbox Code Playgroud)

看到我们得到了我们要求的结构:

Emp(3, 1, [])
Emp(24, null, [Emp(1, 2, []), Emp(6, 7, []), Emp(7, 1, [])])
Emp(25, null, [Emp(1, 1, []), Emp(6, 7, [])])
Run Code Online (Sandbox Code Playgroud)