简体   繁体   English

将java类作为闭包绑定到groovy脚本中

[英]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. 是否可以将用java编写的闭包绑定到groovy脚本中。 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. 把它绑在groovyscript中。

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

and use it in the foo.groovy like this: 并在foo.groovy使用它,如下所示:

example("Hello World")

Done a bit of messing around and came up with this: 做了一点搞乱,想出了这个:

Example.java 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: foo.groovy:

example( 'Hello World' )

and test.groovy: 和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: 然后,我编译java代码:

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

Run the Groovy code: 运行Groovy代码:

groovy -cp . test.groovy

And get the output: 得到输出:

EX: Hello World

edit 编辑

The groovy.lang.Closure class defines 3 variants of call: groovy.lang.Closure类定义了3个调用变体:

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 我覆盖了第二个,但根据您的用例,您可能需要其他任何一个或全部

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM