Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
7
rated 0 times [  13] [ 6]  / answers: 1 / hits: 21041  / 14 Years ago, fri, october 22, 2010, 12:00:00

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)


More From » java

 Answers
132
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();
}

[#95212] Wednesday, October 20, 2010, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
lizette

Total Points: 252
Total Questions: 91
Total Answers: 103

Location: Sint Maarten
Member since Tue, Mar 29, 2022
2 Years ago
;