Java code cannot invoke method from scriptengine with new context -


i trying implement example invoking method javascript in java.

private static final string js = "function doit(p) { list.add(p); return true; }";  public static void main(string[] args) throws scriptexception, nosuchmethodexception {     list<string> list = new arraylist<>();       scriptenginemanager scriptmanager = new scriptenginemanager();     scriptengine engine = scriptmanager.getenginebyname("nashorn");      scriptcontext context = new simplescriptcontext();     context.setbindings(engine.createbindings(), scriptcontext.engine_scope);     bindings scope = context.getbindings(scriptcontext.engine_scope);      scope.put("list", list);     engine.eval(js, context);      invocable invocable = (invocable) engine;     invocable.invokefunction("doit", "hello!!!");      system.out.println(list.size()); } } 

this code throws exception:

exception in thread "main" java.lang.nosuchmethodexception: no such function doit     @ jdk.nashorn.api.scripting.scriptobjectmirror.callmember(scriptobjectmirror.java:204)     @ jdk.nashorn.api.scripting.nashornscriptengine.invokeimpl(nashornscriptengine.java:383)     @ jdk.nashorn.api.scripting.nashornscriptengine.invokefunction(nashornscriptengine.java:190)     @ testjavascriptinteraction.testjavascript.main(testjavascript.java:32) 

version

java -version openjdk version "1.8.0_91" openjdk runtime environment (build 1.8.0_91-8u91-b14-3ubuntu1~16.04.1-b14) openjdk 64-bit server vm (build 25.91-b14, mixed mode) 

what wrong?

i can reproduce problem, , have found way how solve it.

i had hunch after casting invocable, engines own scripting context still being used, , not temporary 1 have passed eval.

i can fix calling engine.setcontext(...) context before casting invacable. i.e.:

... scope.put("list", list); engine.eval(js, context); // 'context' contains 'doit' function.  engine.setcontext(context); // <-- right here invocable invocable = (invocable) engine; // invocable use 'context'. invocable.invokefunction("doit", "hello!!!"); //runs fine  system.out.println(list.size()); 

the fact works seems confirm hunch.


Comments

Popular posts from this blog

unity3d - Rotate an object to face an opposite direction -

angular - Is it possible to get native element for formControl? -

javascript - Why jQuery Select box change event is now working? -