我有同樣的問題,只是在如果你還沒有找到答案。我認爲下面的代碼片段可能包含你想要的。我使用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文檔現在相當糟糕,所以我希望這可能會有所幫助。
犀牛不會接受在JS「與」任意的Java對象,雖然。因此我的問題。 – Kong