Hi all,
I am new to Rhino and the documentation on the website and the newsgroups that I searched did not yield me the answer I was looking for, so I am posting here. I am sorry if this question has already been asked before.
I have a very basic problem which I couldn’t find documentation on how to solve. I am simplifying the example here. Suppose I have a JS file with the following content:
// jscode.js
function add(v1, v2)
{
return v1+v2;
}
function subtract(v1, v2)
{
return v1-v2;
}
I used Rhino to compile this JS script to a Java .class file with the following command:
java –classpath rhino.jar;. org.mozilla.javascript.tools.jsc.Main jscode.js
This produced for me a Java class file called “jscode.class”.
Now I want to be able to invoke the two functions in this javascript code “add” and “subtract”, but from my Java application. That is, I want to be able to do something like the following:
public class TestJSCode
{
public static void main(String[] args)
{
Context cx = Context.enter();
try
{
Scriptable scope = cx.initStandardObjects();
// use the scope and context to invoke the add or subtract functions that are in jscode.js and obtain the result
}
catch ( Exception ex )
{
}
finally
{
Context.exit();
}
}
}
However, I am not sure how to proceed with using the scope and context to invoke the “add” and “subtract” functions that I have in my jscode.js file. I saw on the Rhino documentation page how to do this by passing in the entire JS application as a string to the context.executeString() call, but I don’t see how to do that with a script that has been compiled to a java class file.
Any help or sample code would be much appreciated.
Thank you very much,
Ali
######## First.js ################
function testFunc2() {
return "Func2!";
}
####### FirstWrapper.java #################
import org.mozilla.javascript.Context;
import org.mozilla.javascript.Function;
import org.mozilla.javascript.Script;
import org.mozilla.javascript.Scriptable;
import org.COMPANY.First; //my compiled class
...
Context cx = Context.enter();
Scriptable scope = cx.initStandardObjects();
// create compiled script object
Script f = new First();
//I don't know how to load object, but exec loads it. Any ideas?
f.exec(cx, scope);
Object obj = scope.get("testFunc2", scope);
if (obj instanceof Function) {
Function new_name = (Function) obj;
// call function, null - arguments
Object obj1 = new_name.call(cx, scope, scope, null);
System.out.println(obj1);
} else {
System.out.println("Error: This is not a function!");
}
########################################
I need any meanings...