1

我想创建一个像这样的 groovy 类 og 脚本:

//...
def slurper = new ConfigSlurper().parse(someFile)
//...
//The exact method declaration
def methodCall(def arg){
   //Whatever i want to do
}
//Maybe it is easier with methodMissing
def methodMissing(def args) {
   //Whatever i want to do
}

要 slurp 的文件可能如下所示:

some {
   property = methodCall("with arg")
}

问题是我如何将“methodCall”委托给使用 configslurper 解析的类或脚本?目前它会给你一个methodMissing。

4

2 回答 2

2

我认为这篇博客文章有一个你想要做什么的例子。它比 a 更复杂,methodMissing但可以完成。

于 2013-04-17T19:57:17.647 回答
1

感谢 Sérgio Michels 链接,我找到了解决方案:

public class ScriptWithMethods extends Script {

   String scriptText;

   public ScriptWithMethods(File file) {
      scriptText = file.text
   }

   public void run() {
      GroovyShell shell = new GroovyShell();
      Closure closure = shell.evaluate("{it->$string}");
      closure.resolveStrategy = Closure.DELEGATE_FIRST
      closure.delegate = this
      closure.call()
   }

   def methodCall(def arg){
      //Whatever i want to do
   }
}

//...
def script = new ScriptWithMethods(scriptText:someFile)
def slurper = new ConfigSlurper().parse(script)

当然,您也可以使用“缺少方法”,但这适用于我的用例

于 2013-04-18T19:21:46.987 回答