views:

204

answers:

1

Is it possible to bind a closure written in java into a groovy-script. Is there an interface or something to implement so i can provide a closure?

Something like this?

public class Example implements Closure {
   public void closure(Object... args) {
       System.out.println(args[0]);
   }
}

Bind this into the groovyscript.

Binding binding = new Binding();
binding.put("example", new Example());
groovyScriptEngine.run("foo.groovy", binding)

and use it in the foo.groovy like this:

example("Hello World")
+2  A: 

Done a bit of messing around and came up with this:

Example.java

import groovy.lang.Closure ;

public class Example extends Closure {
  public Example( Object owner, Object thisObject ) {
    super( owner, thisObject ) ;
  }

  public Example( Object owner ) {
    super( owner ) ;
  }

  public Object call( Object params ) {
    System.out.println( "EX: " + params ) ;
    return params ;
  }
}

foo.groovy:

example( 'Hello World' )

and test.groovy:

import groovy.lang.Binding
import groovy.util.GroovyScriptEngine

Binding binding = new Binding()
binding.example = new Example( this )
GroovyScriptEngine gse = new GroovyScriptEngine( [ '.' ] as String[] )
gse.run( "foo.groovy", binding )

Then, I compile the java code:

javac -cp ~/Applications/groovy/lib/groovy-1.7.1.jar Example.java

Run the Groovy code:

groovy -cp . test.groovy

And get the output:

EX: Hello World

edit

The groovy.lang.Closure class defines 3 variants of call:

Object call()
Object call(Object arguments)
Object call(Object[] args) 

I override the second one, but depending on your use-case, you might need any or all of the others

tim_yates
Thank you this was very helpful. Note, you can also null the owner Script in Closure Implementation, so you can bind it from Java.
codedevour
Is it also possible to bind a external Groovy closure into a Groovy Script?
codedevour
you mean bind a script into a script?
tim_yates