失败 Eval.me 将搜索不在它所在的类中的字段



我正在尝试读取具有解析名称的变量的值:

class GatewayFunctionBuilder{
private String responseClass
.....
String target = 'esponse'
println "writing r${target}Class"
println responseClass
String targetClass = Eval.me("r${target}Class")

结果是:

writing responseClass
MWFtest0A1Response
:application:generateJavaFromTestMwf FAILED
FAILURE: Build failed with an exception.
* Where:
Script 'C:Users543829657workspacedev.appl.ib.cblapplicationXml2Java.gradle' line: 53
* What went wrong:
Execution failed for task ':application:generateJavaFromTestMwf'.
> No such property: responseClass for class: Script1

打印变量的内容是正确的。但似乎,Eval.me 不是在调用它的类中搜索 responseClass 字段,而是从 Gradle 任务脚本中搜索。

如果我将此对象作为参数传递,它可以工作:

String targetClass = Eval.x(this, "x.r${target}Class")

但这没有任何逻辑,因为this也不是任务脚本的字段,而是仅对该类的一个实例具有正确意义的东西。即使该实例是在任务脚本中创建的(作为局部变量(,它在那里也有其他名称。

我在 Eval 文档中没有看到任何提及,它在某些"Script1"的上下文中评估字符串

Groovy 2.4.4 中的Eval代码在这里。我们观察到以下内容:

class Eval { ...
public static Object me(final String expression) throws CompilationFailedException {
return me(null, null, expression);
}

和:

public static Object me(final String symbol, final Object object, final String expression) throws CompilationFailedException {
Binding b = new Binding();
b.setVariable(symbol, object);
GroovyShell sh = new GroovyShell(b);
return sh.evaluate(expression);
}

因此,该行为可以在纯 Groovy 中重现,而无需 Gradle:

// Eval.me(expression) == Eval.me(null, null, expression)
def symbol = null
def object = null
def responseClass = "hello"
def target = "esponse"
def expression = "r${target}Class"
def b = new Binding();
b.setVariable(symbol, object);
def sh = new GroovyShell(b);
println sh.evaluate(expression);

很明显,expression不会在Binding对象中找到。

最新更新