我遇到了同样的问题,以防万一您还没有找到答案。我认为以下代码片段可能包含您想要的内容。我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 文档现在非常糟糕,所以我希望这可能会有所帮助。