Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/53.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用groovy Eval处理生成的表达式_Groovy_Eval - Fatal编程技术网

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

使用groovy Eval处理生成的表达式,groovy,eval,Groovy,Eval,我试图创建一个字段映射,将字段从用户友好的名称映射到各种域对象中的成员变量。更大的背景是,我正在基于存储在数据库中的用户构造的规则构建ElasticSearch查询,但出于以下目的: 评估失败。以下是输出: 123 ${target.amount} Caught: groovy.lang.MissingPropertyException: No such property: valueSource for class: Script1 groovy.lang.MissingPropertyExc

我试图创建一个字段映射,将字段从用户友好的名称映射到各种域对象中的成员变量。更大的背景是,我正在基于存储在数据库中的用户构造的规则构建ElasticSearch查询,但出于以下目的:

评估失败。以下是输出:

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
中的实际表达式,但这也可能是扭曲的。

你就快到了,但你需要使用稍微不同的机制:
GroovyShell
。您可以实例化
GroovyShell
,并使用它作为脚本对
字符串
求值,并返回结果。以下是您的示例,经过修改后可以正常工作:

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

我认为
evaluate()
可能会起作用,但这只适用于脚本,在grails应用程序的上下文中不起作用。这些方法不知道从哪个范围调用它们。要使
valueSource
可用,您必须使用
symbol
object
调用
Eval.me
,或者调用
x
/
xy
/
xyz
方法之一。我一直在看文档。谢谢
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