MelonBlog

Java执行Groovy脚本

添加依赖

<dependency>
    <groupId>org.codehaus.groovy</groupId>
    <artifactId>groovy</artifactId>
    <version>3.0.19</version>
</dependency>

执行一个groovy脚本

public class GroovyExecutor {
    public static final String DIR = "commands/";
    public static void execute(String script) {
        try (FileReader fileReader = new FileReader(DIR + script + ".groovy")) {
            GroovyShell shell = new GroovyShell();
            shell.evaluate(fileReader);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    public static void main(String[] args) {
        execute("test");
    }
}

commands/test.groovy

println "Hello World!"

执行一个groovy脚本中的函数

public static void executeScriptMethod(String scriptName) {
      try (GroovyClassLoader cl = new GroovyClassLoader()) {
          Class<?> scriptClass = cl.parseClass(new File(DIR + scriptName + ".groovy"));
          //scriptClass.getMethod("run", Object.class).invoke(scriptClass.newInstance(), "groovy");
					scriptClass.getMethod("run", Object.class).invoke(null, "groovy"); // 静态方法不需要实例
      } catch (Exception e) {
          throw new RuntimeException(e);
      }
  }

commands/test.groovy

class Command {
    static def run(Object param) {
        println "Hello " + param
    }
}