小编典典

从Java代码调用外部JavaScript函数

javascript

通过使用Java Scripting
API,我能够在Java中执行JavaScript。但是,有人可以解释一下我需要添加到此代码中以便能够调用C:/Scripts/Jsfunctions.js中的函数吗?

import javax.script.*;

public class InvokeScriptFunction {
public static void main(String[] args) throws Exception {
    ScriptEngineManager manager = new ScriptEngineManager();
    ScriptEngine engine = manager.getEngineByName("JavaScript");

    // JavaScript code in a String
    String script1 = (String)"function hello(name) {print ('Hello, ' + name);}";
    String script2 = (String)"function getValue(a,b) { if (a===\"Number\") return 1; 
                     else return b;}";
    // evaluate script
    engine.eval(script1);
    engine.eval(script2);

    Invocable inv = (Invocable) engine;

    inv.invokeFunction("hello", "Scripting!!" );  //This one works.      
 }
}

阅读 687

收藏
2020-05-01

共1个答案

小编典典

使用ScriptEngine.eval(java.io.Reader)读剧本

ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("JavaScript");
// read script file
engine.eval(Files.newBufferedReader(Paths.get("C:/Scripts/Jsfunctions.js"), StandardCharsets.UTF_8));

Invocable inv = (Invocable) engine;
// call function from script file
inv.invokeFunction("yourFunction", "param");
2020-05-01