Calling a Groovy function from Java

Viewed 47741

How do you call a function defined in a Groovy script file from Java?

Example groovy script:

def hello_world() {
   println "Hello, world!"
}

I've looked at the GroovyShell, GroovyClassLoader, and GroovyScriptEngine.

6 Answers

You too can use the Bean Scripting Framework to embed any scripting language into your Java code. BSF give you the opportunity of integrate other languages, but is not native integration.

If you are clearly focused to use Groovy the GroovyScriptEngine is the most complete solution.

=)

Just more elegant ways:

GroovyScriptEngine engine = new GroovyScriptEngine( "." )

Object instance = engine
  .loadScriptByName(scriptName)
  .newInstance()

Object result = InvokerHelper.invokeMethod(instance, methodName, args)

And if script class extends groovy.lang.Script:

Object result = engine
  .createScript(scriptName, new Binding())
  .invokeMethod(methodName, args)

No need to extend groovy.lang.Script if you just want call main method of your groovy class:

Object result = engine
  .createScript(scriptName, new Binding())
  .run()
Related