Groovy DSL:当我创建内部DSL时,如何重载Groovy中的任何()
我创建内部DSL,并从DefaultGroovyMethods重载任何()方法Groovy DSL:当我创建内部DSL时,如何重载Groovy中的任何(),groovy,dsl,Groovy,Dsl,我创建内部DSL,并从DefaultGroovyMethods重载任何()方法 class RulesProcessor { } Any live cell with fewer than two live neighbours dies 最后一行是我的DSL。我尝试了propertyMissing、methodMissing、创建我的Any类RulesProcessor.metaClass.Any、DefaultGroovyMethods.metaClass.Any,但它们不起作用 我如
class RulesProcessor {
}
Any live cell with fewer than two live neighbours dies
最后一行是我的DSL。我尝试了propertyMissing、methodMissing、创建我的Any类RulesProcessor.metaClass.Any、DefaultGroovyMethods.metaClass.Any,但它们不起作用
我如何编写代码来接受我的DSL?“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']],
]
对编译器配置的赞誉
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']],
]