2016-08-10 3 views
1

사용자 친숙한 이름의 필드를 다양한 도메인 객체의 멤버 변수에 매핑하는 필드 매핑을 만들려고합니다.groovy Eval을 사용하여 생성 된 표현식 처리

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') 

평가 후면 실패 : 큰 맥락은 내가 데이터베이스에 저장된 사용자 구성의 규칙에 기반하여 ElasticSearch 쿼리를 구축하지만, MCVE을 위해있어 것입니다. 생성 된 변수 이름을 평가하고 값 123을 반환 할 필요가 무엇

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) 

: 여기에 출력입니까? 진짜 문제는 마치 valueSource이 실제로 정의 된 것이 아니라 실제로 valueSource이라는 것을 인식하지 못하는 것입니다.하지만 그럴 수도 있습니다.

+0

'evaluate()'이 효과가 있을지도 모르겠지만 이는 스크립트 용이며 grails 앱의 컨텍스트에서는 작동하지 않습니다. –

+0

평가를위한 [docs] (http://docs.groovy-lang.org/latest/html/api/groovy/util/Eval.html)를보십시오. 메서드는 호출하는 범위를 인식하지 못합니다. 'valueSource'를 사용 가능하게 만들려면'symbol'과'object'를 사용하여'Eval.me'를 호출하거나'x' /'xy' /'xyz' 메소드 중 하나를 호출해야합니다. – hsan

+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 
관련 문제