How to invoke a Groovy script in Java?
To call a Groovy script in Java, you need to use the Groovy compiler and runtime environment.
Here is a simple example demonstrating how to call a Groovy script in Java.
- Firstly, make sure your project includes the dependencies for Groovy. You can use build tools like Maven or Gradle to add Groovy dependencies.
- Create a Groovy script file, such as “example.groovy,” and write your Groovy script content. For example:
def greet(name) {
"Hello, $name!"
}
- In Java code, use the Groovy compiler and runtime environment to load and execute Groovy scripts. For example:
import groovy.lang.GroovyClassLoader;
import groovy.lang.GroovyObject;
public class Main {
public static void main(String[] args) throws Exception {
// 创建GroovyClassLoader
GroovyClassLoader classLoader = new GroovyClassLoader();
// 加载Groovy脚本类
Class<?> groovyClass = classLoader.parseClass(new File("example.groovy"));
// 创建Groovy脚本对象
GroovyObject groovyObject = (GroovyObject) groovyClass.getDeclaredConstructor().newInstance();
// 调用Groovy脚本方法
String result = (String) groovyObject.invokeMethod("greet", "John");
// 输出结果
System.out.println(result);
}
}
In this example, we utilize the GroovyClassLoader to load and parse Groovy script files. We then instantiate the Groovy script class using reflection and invoke its methods.
Please note that you may need to adjust the file paths in the code based on your project structure and file paths.
This is just a simple example, you can perform more complex operations according to your needs.