如何实现NashornScriptEngine?

问题描述 投票:0回答:1

在我正在进行的项目中,我们将使用Nashorn,因此我需要创建此脚本引擎。任何人都可以建议,创建NashornScriptEngine涉及的步骤是什么?请指明步骤。

java java-8 nashorn
1个回答
0
投票

按照示例:您可以关注我的示例@github https://github.com/jamesmedice/Spring-boot---React-js

import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

import jdk.nashorn.api.scripting.NashornScriptEngine;

    private ThreadLocal<NashornScriptEngine> engineHolder = new ThreadLocal<NashornScriptEngine>() {
    @Override
    protected NashornScriptEngine initialValue() {
        NashornScriptEngine nashornScriptEngine = (NashornScriptEngine) new ScriptEngineManager().getEngineByName("nashorn");
        try {
        nashornScriptEngine.eval(read("static/nashorn-polyfill.js"));
        nashornScriptEngine.eval(read("your_js_file.js")); 
        } catch (ScriptException e) {
        throw new RuntimeException(e);
        }
        return nashornScriptEngine;
    }
    };


private Reader read(String path) {
InputStream in = getClass().getClassLoader().getResourceAsStream(path);
return new InputStreamReader(in);
}
© www.soinside.com 2019 - 2024. All rights reserved.