Search code examples
javajavascriptmozillarhino

How can i call a child property function using Apache Rhino


If i have a js object such as below stored in a js file

var _sampleProcessor = {
    process: function(data){
        ...
    }

}

How would i use Apache Rhino to call the process function?

// sb holds the contents of the js file
Context cx = Context.enter();
Scriptable scope = cx.initStandardObjects();
cx.evaluateString(scope, sb.toString(), "Test", 1, null);

Object processor = scope.get("sampleProcessor ", scope);
if (processor  == Scriptable.NOT_FOUND) {
    System.out.println("processor  is not defined.");
}

Getting to the root of the object is easy, but how do i traverse the object tree to get at the process function property

Thanks in advance


Solution

  • This sample does a few things. Pulls out the sampleProcessor as your example does, and also pulls out the process property and executes that function.

    It also shows adding Java objects into the scope so they can be used - the System.out object in the example.

    package grimbo.test.rhino;
    
    import org.mozilla.javascript.Context;
    import org.mozilla.javascript.Function;
    import org.mozilla.javascript.Scriptable;
    import org.mozilla.javascript.ScriptableObject;
    
    public class InvokeFunction {
        public static void main(String[] args) {
            String sb = "var sampleProcessor = {\n" + "    process: function(data){\n    out.println(0); return 1+1;\n    }\n" + "}";
    
            Context cx = Context.enter();
            Scriptable scope = cx.initStandardObjects();
    
            Object out = Context.javaToJS(System.out, scope);
            ScriptableObject.putProperty(scope, "out", out);
    
            cx.evaluateString(scope, sb.toString(), "Test", 1, null);
    
            // get the sampleProcessor object as a Scriptable
            Scriptable processor = (Scriptable) scope.get("sampleProcessor", scope);
            System.out.println(processor);
    
            // get the process function as a Function object
            Function processFunction = (Function) processor.get("process", processor);
            System.out.println(processFunction);
    
            // execute the process function
            Object ob = cx.evaluateString(scope, "sampleProcessor.process()", "Execute process", 1, null);
            System.out.println(ob);
        }
    }
    

    Output:

    [object Object]
    org.mozilla.javascript.gen.Test_1@b169f8
    0.0
    2