脚本scriptText.groovy内容如下:
def cal(int a, int b){
return a+b
}
java调用groovy脚本文件
import java.io.File;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import groovy.lang.GroovyClassLoader;
import groovy.lang.GroovyObject;
import groovy.lang.GroovyShell;
public class Main {
private static Logger logger = LoggerFactory.getLogger(Main.class);
public static void main(String[] args) throws Exception {
// 方法一:使用GroovyClassLoader动态加载脚本
GroovyClassLoader classLoader = new GroovyClassLoader();
Class groovyClass = classLoader.parseClass(new File("src/main/resources/scriptText.groovy"));
try {
Object[] paras = { 1, 2 };
GroovyObject groovyObject = (GroovyObject) groovyClass.newInstance();
int res = (int) groovyObject.invokeMethod("cal", paras);
System.out.println(res);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
// 方法二:使用GroovyShell
Object[] paras = { 1, 2 };
var s = (int) new GroovyShell().parse(new File("src/main/resources/scriptText.groovy")).invokeMethod("cal",paras);
System.out.println(s);
}
}