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)
Calling a JavaScript source in Java is pretty simple. If we develop a Java application in which we must use JavaScript, we will create the script file separately, then include and call it in the Java source to run the desired function.
Rhino is a JavaScript engine written fully in Java and managed by the Mozilla Foundation as open source software. It is separate from the SpiderMonkey engine, which is also developed by Mozilla, but written in C++ and used in Mozilla Firefox.
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With