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

时间:2016-08-10 16:13:33

标签: groovy eval

我试图创建一个字段映射,将用户友好名称中的字段映射到各种域对象中的成员变量。更大的上下文是我根据存储在数据库中的用户构造规则构建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')

Eval失败了。这是输出:

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)

评估生成的变量名称并返回值123需要做些什么?似乎真正的问题是,它没有认识到valueSource已被定义,而不是valueSource中保存的实际表达,但也可能会扭曲。

1 个答案:

答案 0 :(得分:2)

你几乎就在那里,但你需要使用稍微不同的机制: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