Search code examples
javajavascriptrhinofunction-call

Call external javascript functions from java code


By using Java Scripting API, I am able to execute JavaScript within Java. However, can someone please explain what I would need to add to this code in order to be 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 = "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.      
 }
}

Solution

  • 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");