1

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

5
  • 1
    You can get rid of the .put calls. And instead call invokeFunction("add", 3, 5) Commented May 21, 2012 at 11:44
  • It worked. Than you! But if I can ask something else.. I won't always know how many parameters the method has. Any suggestions on how to solve this? Commented May 21, 2012 at 11:54
  • See the answer below (by @Dan Howard) Commented May 21, 2012 at 11:56
  • In JavaScript you mean? Check this link: stackoverflow.com/questions/4138012/… Commented May 21, 2012 at 11:59
  • Btw, if you want to get a return value you'll need to have a return sum; statement in your JavaScript function definition. The return value will appear as return value of invokeFunction and needs to be cast (double) or sth. Commented May 21, 2012 at 12:04

1 Answer 1

2

This works for me:

Object params[] = {1,2,3};
Invocable invocable = (Invocable) script.getEngine();
invocable.invokeFunction("myFunction", params);
Sign up to request clarification or add additional context in comments.

1 Comment

invocable.invocableEngine should probably be invocableEngine.invokeFunction

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.