通过使用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 = "function hello(name) {print ('Hello, ' + name);}";
String script2 = "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.
}
}
URL fileUrl = getClass().getResource("js/WebWorker.js"); engine.eval(Files.newBufferedReader(Paths.get(fileUrl.toURI()),StandardCharsets.UTF_8));
- Manoengine.eval(Files.newBufferedReader(Paths.get("/Volumes/Bala/Eclipse Mars/Workspace/ClientWebAccessFullHistory/war/js/Library/Moment.js"), StandardCharsets.UTF_8)); engine.eval(Files.newBufferedReader(Paths.get("/Volumes/Bala/Eclipse Mars/Workspace/ClientWebAccessFullHistory/war/js/newLayout/FullHistory/fullHistory.js"), StandardCharsets.UTF_8));
但它在全局范围内不可用。 - Bala.Rajload('path/to/Moment.js');
。 - Ben