Groovy DSL - 用于创建对象的快捷方式

Aym*_*man 3 dsl groovy

是否有一种方法在Groovy中替换一些代码,如下所示:

Task a = new Task('a')
Process p = new Process('p')
Run Code Online (Sandbox Code Playgroud)

更轻松的事情,如:

task a
process p
Run Code Online (Sandbox Code Playgroud)

where taskprocesscan方法调用可以创建对象并将其返回或添加到脚本Map中.

我目前的主要问题是我无法使用,a因为它没有定义.

ata*_*lor 5

要创建对象并为其命名而不分配变量,可以使用绑定.创建并保持对闭包绑定的引用,并使用实用程序方法task并将process新实例与名称相关联.例如:

def scriptBinding = new Binding()

def task = { String name ->
    scriptBinding[name] = new Task(name)
}
def process = { String name ->
    scriptBinding[name] = new Process(name)
}

def script = {
    task 'a'
    process 'b'

    println a
    println b
}
script.binding = scriptBinding
script()
Run Code Online (Sandbox Code Playgroud)

请注意,您必须引用它们a,b因此它们被解释为字符串而不是未定义的变量.如果您想省略引号,可以使用自定义Binding对象来计算未定义的符号作为它们的字符串表示,如下所示:

class SymbolAsStringBinding extends Binding {
    Object getVariable(String name) {
        try {
            super.getVariable(name)
        } catch (MissingPropertyException e) {
            name
        }
    }

    boolean hasVariable(String name) {
        true
    }
}
Run Code Online (Sandbox Code Playgroud)

通过添加,您可以将脚本编写为:

def script = {
    task a
    process b

    println a
    println b
}
Run Code Online (Sandbox Code Playgroud)

  • 你也可以使用`def propertyMissing(String p){p}`来避免自定义绑定,并且已经将变量解析为字符串 (2认同)