0

为简单起见,假设我有类似这样的代码:

def testMethod(String txt) {
    return txt;
}
public String evaluate(String expression) {
    //String result = "${testMethod('asdasdasd')}";
    String result = "${expression}";
    return result;
}

我需要执行传递给方法“evaluate”的表达式值。

在打电话的情况下

// everything works perfectly well,
String result = "${testMethod('samplestring')}"; 

在打电话的情况下

// (when expression = testMethod) - everything works perfectly well,
String result = "${expression}"("samplestring"); 

在打电话的情况下

// (when expression = testMethod('samplestring'))  - it's not working.
// I see testMethod('samplestring') as the result, but I need it to be evaluated.
String result = "${expression}" 

我怎样才能做到这一点?谢谢。

4

2 回答 2

1

因此也应该起作用;

Eval.me( "${expression}" )

编辑

正如所指出的那样,这将无法正常工作,您需要传入包含该方法的脚本,Eval.x如下所示:

def testMethod(String txt) {
    txt
}

public String evaluate(String expression) {
    String result = Eval.x( this, "x.${expression}" )
    result
}

println evaluate( "testMethod('samplestring')" )

那将打印samplestring

于 2011-11-02T19:14:36.277 回答
0

您可以GroovyShell为此目的使用该类,但您需要定义一个 Binding AFAIK。这适用于 Groovy 控制台:

def testMethod(txt) {
    "$txt!";
}

def evaluate(String expression) {
    def binding = new Binding(['testMethod': testMethod])
    new GroovyShell(binding).evaluate(expression)
}

evaluate('testMethod("Hello World")');
于 2011-11-02T18:33:29.990 回答