从 java 代码调用外部 javascript 函数
2022-08-31 21:01:46
通过使用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.
}
}