我基本上想去:
ScriptObjectMirror myObj = new ConcreteScriptObjectMirror();
然后像这样调用一些JS,其中myObj
是参数:
function myJSFunc(param) {
with(param) {
return paramProperty;
}
}
我现在正在这样做,但 Nashorn 正在提示:
TypeError: Cannot apply "with" to non script object
所以我传入的Java对象需要是ScriptObjectMirror的一个实例。
最佳答案
我遇到了同样的问题,以防万一您还没有找到答案。我认为以下代码片段可能包含您想要的内容。我正在使用 javax.script.SimpleBindings
将对象传递给 JavaScript 函数。
import javax.script.Compilable;
import javax.script.CompiledScript;
import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import javax.script.SimpleBindings;
public class Demo {
public static void main(String[] args) throws Exception {
Demo demo = new Demo();
String result = demo.execute();
System.out.println("full name is " + result);
}
public String execute() throws ScriptException, NoSuchMethodException {
final ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
final Compilable compilable = (Compilable) engine;
final Invocable invocable = (Invocable) engine;
final String statement = "function fetch(values) { return values['first_name'] + ' ' + values['last_name']; };";
final CompiledScript compiled = compilable.compile(statement);
compiled.eval();
SimpleBindings test = new SimpleBindings();
test.put("first_name", "John");
test.put("last_name", "Doe");
FullName fullName = invocable.getInterface(FullName.class);
return fullName.fetch(test);
}
public interface FullName {
String fetch(SimpleBindings values);
}
}
恕我直言,Nashorn 文档目前非常糟糕,所以我希望这可能有所帮助。
关于java - Java 中是否有 Nashorn 的 ScriptObjectMirror 的公共(public)和具体实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24691142/