java - 从 Java 调用 Groovy 函数

标签 java groovy

如何从 Java 调用 Groovy 脚本文件中定义的函数?

示例 groovy 脚本:

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

我查看了 GroovyShell、GroovyClassLoader 和 GroovyScriptEngine。

最佳答案

假设您有一个名为 test.groovy 的文件,其中包含(如您的示例):

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

然后你可以像这样创建一个文件Runner.java:

import groovy.lang.GroovyShell ;
import groovy.lang.GroovyClassLoader ;
import groovy.util.GroovyScriptEngine ;
import java.io.File ;

class Runner {
  static void runWithGroovyShell() throws Exception {
    new GroovyShell().parse( new File( "test.groovy" ) ).invokeMethod( "hello_world", null ) ;
  }

  static void runWithGroovyClassLoader() throws Exception {
    // Declaring a class to conform to a java interface class would get rid of
    // a lot of the reflection here
    Class scriptClass = new GroovyClassLoader().parseClass( new File( "test.groovy" ) ) ;
    Object scriptInstance = scriptClass.newInstance() ;
    scriptClass.getDeclaredMethod( "hello_world", new Class[] {} ).invoke( scriptInstance, new Object[] {} ) ;
  }

  static void runWithGroovyScriptEngine() throws Exception {
    // Declaring a class to conform to a java interface class would get rid of
    // a lot of the reflection here
    Class scriptClass = new GroovyScriptEngine( "." ).loadScriptByName( "test.groovy" ) ;
    Object scriptInstance = scriptClass.newInstance() ;
    scriptClass.getDeclaredMethod( "hello_world", new Class[] {} ).invoke( scriptInstance, new Object[] {} ) ;
  }

  public static void main( String[] args ) throws Exception {
    runWithGroovyShell() ;
    runWithGroovyClassLoader() ;
    runWithGroovyScriptEngine() ;
  }
}

编译它:

$ javac -cp groovy-all-1.7.5.jar Runner.java 
Note: Runner.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.

(注意:警告留给读者作为练习);-)

然后,您可以运行这个 Runner.class:

$ java -cp .:groovy-all-1.7.5.jar Runner
Hello, world!
Hello, world!
Hello, world!

关于java - 从 Java 调用 Groovy 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3989592/

相关文章:

java - 为什么我收到以下异常

Java 窗口 "could not find or load main class"

grails - 如何导出Config.groovy中相对目录的物理路径?

Java HashMap : A Bug in JVM or I am doing wrong?

java - 为什么 CMD 无法识别 javadoc 命令?

java - 聊天程序卡住 JFrame

Gradle 自定义任务扩展 Exec 抛出错误

java - 使用 Java 从 torrent 中提取元数据

tomcat - 在 gant 脚本中使用(多词位)grails 目标

grails - Grails批处理作业