我发现here是我想要的一个非常好的例子:
基本上能够将String作为带有表达式的groovy脚本执行,但如果条件为false,我想显示有关它被评估为false的原因的详细信息。
修改
我想要一个像这样工作的实用工具方法:
def expression = "model.book.title == \"The Shining\""
def output = magicMethod(expression)
// output.result: the exact result of executing expression
// output.detail: could be a string telling me why this expression returns true or false, similar to de image
我认为它可能是Eval.me
+ assert
的组合,并且为了获取详细信息而捕获异常
答案 0 :(得分:1)
是的,它适用于断言,感谢@Justin Piper的想法
这是片段:
def model = [model:[book:[title:"The Shinning"]]]
def magicMethod= { String exp ->
def out = [:]
out.result = Eval.x(model,"x.with{${exp}}")
try{
if(out.result){
Eval.x(model,"x.with{!assert ${exp}}")
}else{
Eval.x(model,"x.with{assert ${exp}}")
}
}catch(Throwable e){
out.detail = e.getMessage()
}
return out
}
def expression = "model.book.title == \"The Shining\""
def output = magicMethod(expression)
println "result: ${output.result}"
println "detail: ${output.detail}"