Search code examples
javarhino

Passing parameters to a javascript function


So here's the deal: I read this article and started trying to use Rhino. So far I got how to invoke a function, and how to get its return. What I can't do is pass the function's parameter. Here's my code:

ScriptEngineManager engineMgr = new ScriptEngineManager();
ScriptEngine engine = engineMgr.getEngineByName("ECMAScript");

String js = "";
js += "function add(a, b) {";
js += " var sum = parseFloat(a) + parseFloat(b);";
js += " println(sum);";
js += "}";

engine.put("a", 3);
engine.put("b", 5);

Object returnn = null;
try {
    engine.eval(js);

    Invocable invocableEngine = (Invocable) engine;
    returnn = invocableEngine.invokeFunction("add");
} catch (ScriptException e) {
    System.out.println("Script error.");
} catch (NoSuchMethodException e) {
    System.out.println("Method error.");
}

System.out.println(returnn);

I get no Exception whatsoever, but the return comes back as NaN. I tried printing a and b (The parameters) and they always come as null. If this is not the best way to invoke a function, please just point me to some useful thread. (Which I did not find on my own)

TYVM in advance


Solution

  • This works for me:

    Object params[] = {1,2,3};
    Invocable invocable = (Invocable) script.getEngine();
    invocable.invokeFunction("myFunction", params);