Search code examples
javajavascriptrhino

Calling a function that takes a callback as argument using Rhino


How can I call the following sum() function with Rhino (org.mozilla.javascript, not javax.script), passing it a Java method as a callback (or any other way that would allow me to receive the result back in Java), once I have the Rhino Function object representing it?

function sum(a, b, successHandler) {
    successHandler(a + b);
}

Solution

  • This is the solution I found:

    function.call(context, scope, null, new org.mozilla.javascript.Function() {
        @Override
        public Object call(Context cx, Scriptable scope, Scriptable thisObj, Object[] args) {
            System.out.println(args[0]);
        },
    
        // ...
    });
    

    It's unfortunate that org.mozilla.javascript.Function is such a large interface, but everything seems to work correctly, even if none of the required methods have a real implementation.

    This is not exactly elegant though. I wish there was a better way.