Question

I've been using rhino to allow the customization of some applications. Here is an example of JavaScript function that is called from Java:

        function() {
            var phone = this.telephoneNumber;
            phone = phone.replace(/[^+0-9]/g,"");
            if (phone.indexOf("+") == 0) {
                phone = "00" + phone.substring(1);
            }
            if (phone.indexOf("0041") == 0) {
                phone = "0" + phone.substring(4);
            }
            if (phone.indexOf("0") == 0) {
                phone = "0" + phone;
            }
            return {
                Name: this.sn + " " + this.givenName,
                firstName: this.givenName || "",
                lastName: this.sn || "",
                phone: phone,
                service: "",
                info: ""
            };
        }

The java application can then get the values of the returned object for whatever it needs to do.

Now that rhino is part of the JVM, I would like to use the scripting API instead of the Rhino API, but I haven't found how to get the field values of a JavaScript object from Java code.

Was it helpful?

Solution

This loosely couples the scripting language, but with the caveats that the functions need to be named, and the returned object needs to be a Map (Rhino does this, but I'm not sure about JRuby).

    ScriptEngineManager factory = new ScriptEngineManager();
    ScriptEngine engine = factory.getEngineByName("JavaScript");
    engine.eval("function x() { return { foo: 10 } }");

    Object o = ((Invocable)engine).invokeFunction("x");
    if (o instanceof Map) {
    Map m = (Map<Object, Object>)o;
        System.out.println(m.get("foo"));
    }

or

    CompiledScript script = ((Compilable)engine).compile("(function() { return {bar:20} })()");
    System.err.println(((Map)script.eval()).get("bar"));

But you have to cheat and call your function by padding it with (...)().

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top