Bind java class as closure in groovy - script

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

Something like that?

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

Link this in groovyscript.

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

and use it in foo.groovy as follows:

 example("Hello World") 
+4
source share
1 answer

Made a little mess and came up with the following:

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 java code:

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

Run the Groovy code:

 groovy -cp . test.groovy 

And we get the conclusion:

 EX: Hello World 

change

The groovy.lang.Closure class defines 3 call options:

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

I redefine the second, but depending on your use case, you may need all or all of the rest

+9
source

Source: https://habr.com/ru/post/1305516/


All Articles