我创建了内部 DSL,并且会重载 DefaultGroovyMethods 中的 any() 方法。
class RulesProcessor {
}
Any live cell with fewer than two live neighbours dies
最后一行是我的 DSL。我尝试了 propertyMissing、methodMissing、创建我的 Any 类、RulesProcessor.metaClass.any、DefaultGroovyMethods.metaClass.any,但它们不起作用。
我如何编写代码来接受我的 DSL?对我来说,只有“任何”这个词的第一步很复杂。
最佳答案
如果您可以将其放入闭包中,只需将其委托(delegate)给一个响应任何
方法的对象,或者如我的示例中的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']],
]
感谢mrhaki关于编译器配置。
关于当我创建内部 DSL 时,Groovy DSL : How I can overload any() in Groovy,,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26236986/