0

For simplicity let's say I have code similar to this:

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

I need the expression value which is passed to method "evaluate" to be executed.

in case of calling

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

in case of calling

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

in case of calling

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

How can I do that? Thanks.

tim_yates
  • 167,322
  • 27
  • 342
  • 338
Yuri Dolzhenko
  • 242
  • 2
  • 7

2 Answers2

1

Thus should work as well;

Eval.me( "${expression}" )

Edit

As pointed out, this won't work as it stands, you need to pass in the script that contains the method with Eval.x like so:

def testMethod(String txt) {
    txt
}

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

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

That will print samplestring

tim_yates
  • 167,322
  • 27
  • 342
  • 338
0

You may use the GroovyShell class for this purpose, but you will need to define a Binding AFAIK. This works in the Groovy Console:

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

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

evaluate('testMethod("Hello World")');
epidemian
  • 18,817
  • 3
  • 62
  • 71