从字符串生成闭包需要 Groovy 语法帮助 [英] Need Groovy syntax help for generating a Closure from a String

查看:20
本文介绍了从字符串生成闭包需要 Groovy 语法帮助的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从字符串生成闭包.闭包内的代码引用了一个 DSL 函数 build().我得到的错误暗示 Groovy 正在尝试执行闭包而不是仅仅声明它.什么是正确的语法?以下是我已经尝试过的一些结构.

I'm trying to generate a closure from a string. The code inside the closure references a DSL function build(). The errors I'm getting imply that Groovy is trying to execute the closure instead of just declaring it. What is the correct syntax for this? Here are some of the constructs I have already tried.

sh = new GroovyShell() 
cl = sh.evaluate( '{ build("my job") }' } 
=> Ambiguous expression could be either a parameterless closure expression or an isolated open code block;

sh = new GroovyShell() 
cl = sh.evaluate( 'L: { build("my job") }' } 
=> No signature of method: Script1.build() is applicable ...

cl = Eval.me( 'L: { build("my job") }' } 
=> No signature of method: Script1.build() is applicable ...

cl = Eval.me( 'L: { com.flow.FlowDelegate.build("my job") }' } 
=> No such property: com for class: Script1

我试图遵循的示例来自:从 Groovy 中的字符串加载闭包代码

The example I'm trying to follow comes from: Load closure code from string in Groovy

推荐答案

考虑下面的例子.关键是明确指定一个没有参数的闭包.

Consider the example below. The key is to specify, explicitly, a closure without parameters.

def build = { def jobName ->
    println "executing ${jobName}"
}

// we initialize the shell to complete the example
def sh = new GroovyShell()
sh.setVariable("build", build)

// note "->" to specify the closure
def cl = sh.evaluate(' { -> build("my job") }')

println cl.class
cl.call()

这篇关于从字符串生成闭包需要 Groovy 语法帮助的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆