如果您可以将其放入闭包中,只需将其委托给响应any 方法的对象,或者如我的示例中的invokeMethod:
class Dsl {
def params = []
def invokeMethod(String method, args) {
params << [method, args]
this
}
def propertyMissing(String prop) { prop }
}
a = {
any live cell with fewer than two live neighbours dies
}
dsl = new Dsl()
a.delegate = dsl
a()
assert dsl.params == [
['any', ['live']],
['cell', ['with']],
['fewer', ['than']],
['two', ['live']],
['neighbours', ['dies']],
]
如果您正在从文件中读取脚本,似乎有必要使用显式调用 any 的方法:
import org.codehaus.groovy.control.CompilerConfiguration
class Dsl {
def params = []
def invokeMethod(String method, args) {
params << [method, args]
this
}
def any(param) { invokeMethod('any', [param]) }
def propertyMissing(String prop) { prop }
}
code = 'any live cell with fewer than two live neighbours dies'
parsed = new GroovyShell(
getClass().classLoader,
new Binding(),
new CompilerConfiguration(scriptBaseClass : DelegatingScript.class.name)
).parse( code )
dsl = new Dsl()
parsed.setDelegate( dsl )
parsed.run()
assert dsl.params == [
['any', ['live']],
['cell', ['with']],
['fewer', ['than']],
['two', ['live']],
['neighbours', ['dies']],
]
向 CompilerConfiguration 上的 mrhaki 致敬。