Java调用Groovy脚本

概述

    在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


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值