Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to import a closure from groovy to java?

I'm trying to extract a closure from a groovy script. I define the closure as

def printMe = {str ->println str}

in my groovy file, and then try to use it by grabbing it from the binding as follows:

GroovyScriptEngine gse = new GroovyScriptEngine(new String[] { "scripts" });
Binding binding = new Binding();
gse.run("test.groovy", binding);
Closure cls = (Closure) binding.getVariable("printMe");
cls.call("foo");

But I get the following error when I run this.

groovy.lang.MissingPropertyException: No such property: 
    printMe for class: groovy.lang.Binding
    at groovy.lang.Binding.getVariable(Binding.java:55)
    at GroovyTry.main(GroovyTry.java:19)

Is there a way to grab a closure (or a plain method) from a groovy script?

like image 235
brice Avatar asked Jul 30 '10 10:07

brice


People also ask

What is the use of closure in Groovy?

A closure is an anonymous block of code. In Groovy, it is an instance of the Closure class. Closures can take 0 or more parameters and always return a value. Additionally, a closure may access surrounding variables outside its scope and use them — along with its local variables — during execution.

Can Groovy import Java classes?

Groovy follows Java's notion of allowing import statement to resolve class references.


1 Answers

What happens if you omit the def from your closure declaration?

printMe = { str -> println str }

By using def, I think the printMe variable becomes local to the script, rather than going in the Binding

Read more about Scoping and the Semantics of "def"

like image 136
tim_yates Avatar answered Oct 14 '22 16:10

tim_yates