hjk321 hjk321 - 1 year ago 197
Java Question

Java: Returning an object from ScriptEngine javascript

I'm trying to evaluate javascript in Java by using the ScriptEngine class. Here is a short example of what I am 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 pretty sure that this should work... but I'm stumped, an I'll take any help I can get. Thanks in advance!

Answer Source

Note: The following is for Java 8, using the Nashorn engine.

First, to make the code compile, remove the .value from the println() statement. obj is declared to be type Object, and Object doesn't have a value field.

Once you do that, you get the following exception when running the code:

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

That is because you don't have a function, so you cannot call return. The return value of the script is the value of the last expression, so just say obj.

Now it will run and print [object Object]. To see what type of object you got back, change to println(obj.getClass().getName()). That will print jdk.nashorn.api.scripting.ScriptObjectMirror. I've linked to the javadoc for your convenience.

ScriptObjectMirror implements Bindings which in turn implements Map<String, Object>, so you can call get("value").

Working code is:

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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download