injecting a variable into a ScriptObjectMirror scope

yikes aroni yikesaroni at gmail.com
Thu Apr 20 13:19:52 UTC 2017


I have the feeling this isn't possible, but i want to be sure.

If i have some code essentially like this creating a module with a closure

String code = "(function() {
   var publ={};
   publ.aaa = 123;
   publ.fn = function() {
      print('aaa='+aaa);
      print('bbb='+bbb);   // I want to inject the value of bbb later,
before calling "fn".
   }
   return publ;
}";
ScriptObjectMirror som = scriptEngine.eval(code);

after the creation of the SOM, is it possible for me to inject a variable
"bbb" to the scope of the SOM object so that, when i invoke "fn", it
evaluates the injected value of bbb?

I've tried
      * som.put('bbb', 789);
      * som.setMember('bbb', 789);

I've found that, if fn refers to bbb as "publ.bbb", then i can use
setMember, but this is a restriction that doesn't work for my circumstance.
I understand that there's no bbb in the closure, thus it is probably not
possible, but maybe some Nashorn magic?

thanks for any thoughts.


More information about the nashorn-dev mailing list