Calling a Groovy function from Java

后端 未结 6 1697
猫巷女王i
猫巷女王i 2020-12-05 04:56

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

Example groovy script:

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


        
6条回答
  •  隐瞒了意图╮
    2020-12-05 05:12

    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()
    

提交回复
热议问题