Java通过ScriptEngine 执行js脚本案例

时间:2020-12-27 15:21:10
public static void main(String[] args) throws ScriptException, FileNotFoundException, NoSuchMethodException {
        ScriptEngine engine = new ScriptEngineManager().getEngineByName("javascript");
        
        engine.eval(new FileReader("G:\\tmp\\test.js"));
        
        if(engine instanceof Invocable){
            Invocable in = (Invocable)engine;
            
            Double result = (Double)in.invokeFunction("add", 100.0,200.0);
            
            System.out.println("Result:"+result);
        }
    }