Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bind a java class as a closure into a groovy-script

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")
like image 329
Christopher Klewes Avatar asked Jan 23 '23 08:01

Christopher Klewes


1 Answers

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

like image 176
tim_yates Avatar answered Jan 31 '23 17:01

tim_yates