14

I'm using Mozilla Rhino 1.7r2 (not the JDK version), and I want to call a JS function from Java.

My JS function is like this:

function abc(x,y)
{
 return x+y
}

How do I do this?

Edit: (The JS function is in a separate file)

asked Oct 22, 2010 at 10:21
2
  • mozilla.org/rhino/tutorial.html#callingJSfuns Commented Oct 22, 2010 at 10:47
  • @org That example is not very clear to me. Where do I specify the path of the JS file? I guess it assumes that I'd just type the entire JS code in cmdline and pass it as an arg to my java app! ^^" Commented Oct 22, 2010 at 11:03

1 Answer 1

38
String script = "function abc(x,y) {return x+y;}";
Context context = Context.enter();
try {
 ScriptableObject scope = context.initStandardObjects();
 Scriptable that = context.newObject(scope);
 Function fct = context.compileFunction(scope, script, "script", 1, null);
 Object result = fct.call(
 context, scope, that, new Object[] {2, 3});
 System.out.println(Context.jsToJava(result, int.class));
} finally {
 Context.exit();
}

UPDATE: when the function is loaded in the scope, along with other functions and variables

String script = "function abc(x,y) {return x+y;}"
 + "function def(u,v) {return u-v;}";
Context context = Context.enter();
try {
 ScriptableObject scope = context.initStandardObjects();
 context.evaluateString(scope, script, "script", 1, null);
 Function fct = (Function)scope.get("abc", scope);
 Object result = fct.call(
 context, scope, scope, new Object[] {2, 3});
 System.out.println(Context.jsToJava(result, int.class));
} finally {
 Context.exit();
}
answered Oct 22, 2010 at 10:57
Sign up to request clarification or add additional context in comments.

3 Comments

Don't forget to add this before try block context.setOptimizationLevel(-1);
@Maurice Perry if i want to call function using multidimensional integer array like [[1,3],[4,5],[6,9]] then how can i pass Object[] ?
@SamirMangroliya I guess you would need to call Context.newArray for each inner array, and then one more time for the outer array.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.