当我创建内部 DSL 时,Groovy DSL : How I can overload any() in Groovy,

标签 groovy dsl

我创建了内部 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/

相关文章:

Java动态方法创建

java - 如何使用java6代码计算文件的硬链接(hard link)、所有者和组?

scala - 带尖括号 (<>) 的方法

python - 与 Python 的流畅界面

image-processing - 用于 Clojure 图像合成的 DSL

java - Groovy 语言有 ?.处理NullPointer异常的语法,scala中有类似的东西吗?

unit-testing - Groovy/模拟 SQL

groovy - 如何使用 GrabResolver 在 groovysh 中使用远程存储库

programming-languages - 特定领域语言与函数库

groovy - 在 Groovy 表达式中使用文字运算符(例如 "and"、 "or")?