SeraphimFoA
SeraphimFoA

Reputation: 466

Specific use of Eval to parse a function call with Groovy

I'm receiving in groovy a string in this format:

"function_name(columnOne,columnTwo)"

What I need to achieve is to call the function I have defined in my script (named function_name) and passing to the function "columnOne" and "columnTwo" as String.

Is it possible to achieve that directly with some form of Eval? without the need to split the string and extract the two names?

My function_name will get those 2 column from a dataset, with something like

val1 = a['columnOne']

that's why I need that sequence of character treated as a string.

Any Idea or workaround?

Upvotes: 0

Views: 69

Answers (1)

cfrick
cfrick

Reputation: 37008

DelegatingScript can be used with propertyMissing:

import org.codehaus.groovy.control.CompilerConfiguration

class MyDSL {
    // every property missing will just be returned as a string
    def propertyMissing(final String name) { name }
    // your function with any string arguments
    void function_name(final String... args) {
        println "Called function_name($args)"
    }
 }

CompilerConfiguration cc = new CompilerConfiguration()
cc.setScriptBaseClass('groovy.util.DelegatingScript')
GroovyShell sh = new GroovyShell(getClass().classLoader, new Binding(), cc)
DelegatingScript script = (DelegatingScript)sh.parse("function_name(Between,The,Burried,And,Me)")
script.setDelegate(new MyDSL())
script.run()

Upvotes: 2

Related Questions