By using Java Sripting API, I am able to execute JavaScript within Java. However, can someone please explain what I would need to add to this code for being able to call on functions that are in 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.
}
}
Use ScriptEngine.eval(java.io.Reader)
to read the script
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");
By using Java Sripting API, I am able to execute JavaScript within Java. However, can someone please explain what I would need to add to this code for being able to call on functions that are in 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.
}
}
Use ScriptEngine.eval(java.io.Reader)
to read the script
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");
0 commentaires:
Enregistrer un commentaire