Java: returning an object from ScriptEngine javascript

I am trying to evaluate javascript in Java using the ScriptEngine class . Here is a brief example of what I'm trying to do:

import javax.script.ScriptEngineManager;
import javax.script.ScriptEngine;

public class Test {
    public static void main(String[] args) {
        ScriptEngine engine = new ScriptEngineManager().getEngineByName("js"); //Creates a ScriptEngine
        Object obj = engine.eval("var obj = { value: 1 }; return obj; "); // Evals the creation of a simple object
        System.out.println(obj.value); // I get an invalid token error when trying to print a property of the object
    }
}

I'm sure this should work ... but I'm at a standstill and I will do whatever help I can get.

+4
source share
1 answer

Note. For Java 8, the following Nashorn mechanism is used .

First, to compile the code, remove .valuefrom the instructions println(). objdeclared as a type Object, but Objecthas no field value.

Once you do this, when you run the code, you will get the following exception:

Exception in thread "main" javax.script.ScriptException: <eval>:1:25 Invalid return statement
var obj = { value: 1 };  return obj; 
                         ^ in <eval> at line number 1 at column number 25

, , return. script - , obj.

[object Object]. , , println(obj.getClass().getName()). jdk.nashorn.api.scripting.ScriptObjectMirror. javadoc .

ScriptObjectMirror Bindings, , , Map<String, Object>, get("value").

:

import javax.script.*;

public class Test {
    public static void main(String[] args) throws ScriptException {
        ScriptEngine engine = new ScriptEngineManager().getEngineByName("js");
        Bindings obj = (Bindings)engine.eval("var obj = { value: 1 };  obj; ");
        Integer value = (Integer)obj.get("value");
        System.out.println(value); // prints: 1
    }
}

UPDATE

, , ? .

, :

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;

import jdk.nashorn.api.scripting.ScriptObjectMirror;

public class Test {
    public static void main(String[] args) throws Exception {
        String script = "var f = {\n" +
                        "  value: 0,\n" +
                        "  add: function(n) {\n" +
                        "    this.value += n;\n" +
                        "    return this.value;\n" +
                        "  }\n" +
                        "};\n" +
                        "f; // return object to Java\n";
        ScriptEngine engine = new ScriptEngineManager().getEngineByName("js");
        ScriptObjectMirror obj = (ScriptObjectMirror)engine.eval(script);
        System.out.println("obj.value = " + obj.getMember("value"));
        System.out.println("obj.add(5): " + obj.callMember("add", 5));
        System.out.println("obj.add(-3): " + obj.callMember("add", -3));
        System.out.println("obj.value = " + obj.getMember("value"));
    }
}

obj.value = 0
obj.add(5): 5.0
obj.add(-3): 2.0
obj.value = 2.0
+5

All Articles