java 执行 groovy 脚本 demo

青苗 青苗 | 406 | 2022-12-16

java 执行 groovy 脚本引擎类


import lombok.extern.slf4j.Slf4j;

import javax.script.Bindings;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import java.util.Map;

@Slf4j
public class GroovyScriptEngine {
    private static final ScriptEngine SCRIPT_ENGINE;

    static {
        final ScriptEngineManager factory = new ScriptEngineManager();
        SCRIPT_ENGINE = factory.getEngineByName("groovy");
    }

    public static Object evaluate(String script, Map<String, Object> params) {
        try {
            Bindings bindings = SCRIPT_ENGINE.createBindings();
            bindings.putAll(params);
            return SCRIPT_ENGINE.eval(script, bindings);
        } catch (Exception e) {
            log.error("Groovy脚本执行异常, script:{}, params:{}, {}", script, params, e.getMessage());
            return null;
        }
    }
}

测试类


import java.util.Date;
import java.util.HashMap;

public class GroovyScriptEngineTest {

    public static void main(String[] args) {
        String groovyScript = "def res = date.getTime(); hi + res";
        Object obj = GroovyScriptEngine.evaluate(groovyScript, new HashMap<String, Object>(){{
            put("date", new Date());
            put("hi", "测试");
        }});
        System.out.println(obj);
    }
}

执行结果

33c84193aa88424fa596d6851608b2f9.jpg

文章标签: Java
推荐指数:

真诚点赞 诚不我欺~

java 执行 groovy 脚本 demo

点赞 收藏 评论

关于作者

青苗
青苗

青苗幼儿园园长

等级 LV5

粉丝 19

获赞 47

经验 1182