I had the same problem, and just in case, you have not yet found the answer. I think the following code snippet may contain what you want. I use javax.script.SimpleBindings to pass an object to a JavaScript function.
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); } }
IMHO, the documentation in Nashorn is very bad, so I hope this can be useful.
source share