使用 groovy Eval 处理生成的表达式

Using groovy Eval to process generated expression

我正在尝试创建一个字段映射,以将字段从用户友好的名称映射到各种域对象中的成员变量。更大的上下文是我正在根据存储在数据库中的用户构建的规则构建 ElasticSearch 查询,但为了 MCVE:

class MyClass {
  Integer amount = 123
}

target = new MyClass()
println "${target.amount}"

fieldMapping = [
  'TUITION' : 'target.amount'
]

fieldName = 'TUITION'
valueSource = '${' + "${fieldMapping[fieldName]}" + '}'
println valueSource

value = Eval.me('valueSource')

评估失败。这是输出:

123
${target.amount}
Caught: groovy.lang.MissingPropertyException: No such property: valueSource for class: Script1
groovy.lang.MissingPropertyException: No such property: valueSource for class: Script1
    at Script1.run(Script1.groovy:1)
    at t.run(t.groovy:17)

计算生成的变量名和return值123需要什么?似乎真正的问题是它没有认识到 valueSource 已经被定义,而不是 valueSource 中的实际表达式,但这也可能是扭曲的。

您快完成了,但是您需要使用一种稍微不同的机制:GroovyShell。您可以实例化一个 GroovyShell 并使用它来评估一个 String 作为脚本,返回结果。这是您的示例,经过修改后可以正常工作:

class MyClass {
    Integer amount = 123
}

target = new MyClass()

fieldMapping = [
        'TUITION' : 'target.amount'
]
fieldName = 'TUITION'

// These are the values made available to the script through the Binding
args = [target: target]

// Create the shell with the binding as a parameter
shell = new GroovyShell(args as Binding)

// Evaluate the "script", which in this case is just the string "target.amount".
// Inside the shell, "target" is available because you added it to the shell's binding.
result = shell.evaluate(fieldMapping[fieldName])

assert result == 123
assert result instanceof Integer