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);
}
}
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