在groovy中使用参数调用方法的运行时

时间:2011-11-02 16:56:55

标签: groovy dynamic gstring

为简单起见,我想我的代码类似于:

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}" 

我该怎么做? 感谢。

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

您可以使用GroovyShell类来实现此目的,但您需要定义绑定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")');
相关问题