概述
在Java和Groovy的结合中,经常会碰到需要从Java代码中调起一个写好的Groovy脚本,我们可以通过GroovyShell来实现。其中最重要的就是GroovyShell和Binding两个类,其中GroovyShell可以调起一个Groovy脚本,而Binding可以向脚本里面传递参数。
简单示例
//通过Binding向要执行的groovy脚本传递变量
Binding binding = new Binding();
binding.setVariable("log", log);
binding.setVariable("msg","welcome to china.");//设置变量,挂在binding下
//通过groovyShell调起脚本
GroovyShell shell = new GroovyShell(binding);
String path = "d:\\test.groovy";//脚本位置
File file = new File(path);
log.info("执行Groovy脚本:{}", file.getCanonicalPath());
Object result = shell.evaluate(file);//执行脚本
log.info("Groovy脚本返回:{}", result);
如果是经常使用,更进一步,我们可以封装一个工具类出来:
import groovy.lang.Binding;
import groovy.lang.GroovyShell;
import java.io.File;
import java.io.IOException;
import java.util.Map;
import java.util.Set;
/**
* GroovyShell工具类
* Created by gameloft9 on 2018/2/24.
*/
public class GroovyShellUtil {
/**
* 执行脚本
*
* @param file 脚本文件
* @param args 参数
*/
public static Object executeShellScript(File file, Map<String, Object> args) throws IOException {
//通过Binding向要执行的groovy脚本传递变量
Binding binding = new Binding();
if (args != null && !args.isEmpty()) {
Set<String> keySet = args.keySet();
for (String key : keySet) {
binding.setVariable(key, args.get(key));
}
}
//通过groovyShell调起脚本
GroovyShell shell = new GroovyShell(binding);
return shell.evaluate(file);//执行脚本并返回结果
}
/**
* 执行脚本
*
* @param filePath 脚本文件
* @param args 参数
*/
public static Object executeShellScript(String filePath, Map<String, Object> args) throws IOException {
File file = new File(filePath);
return executeShellScript(file,args);
}
}
工具类里面重载了两个方法,根据file对象或者file路径去调起Groovy脚本。
测试
test.groovy脚本:
def count = 5
def res = 0
(1..<count).each { n->
res += count
}
log.info(msg);
return res;
测试代码:
String path = "d:\\test.groovy";//脚本位置
Map<String,Object> arg = new HashMap<String,Object>();
arg.put("log",log);
arg.put("msg","welcome to china.");
log.info("Groovy脚本返回:{}", GroovyShellUtil.executeShellScript(path,arg));
运行结果:
Demo下载地址:http://download.csdn.net/download/gameloft9/10261273