I am struggling with nashorn
and with
block. I would like to pass 'context' from java with HashMap
and use it in my code. However, I am not able to get this working.
JS to be evaluated
with(ctx) {
return a+b;
}
Java map to be "passed"
Map<Object, Object> ctx = new HashMap<>();
ctx.put("a", 5)
ctx.put("b", 5)
Below I prepared short class to demonstrate errors I am facing to.
public class Test {
public static void main(String[] args) throws ScriptException {
Map<Object, Object> ctx = new HashMap<>();
ctx.put("foo", 5);
eval("print('1st - :)'); ctx = {'foo':'bar'}; with(ctx) {print(foo);}", new HashMap<>());
// No exception with 'with', o seems to be properly 'in context'..
eval("print('2nd - :)'); var o = {}; print(o); with(Object.bindProperties(o, ctx)) { print(o); } print(o)", ctx);
try {
// ..But it is not
eval("print('3rd - :('); var o = {}; with(Object.bindProperties(o, ctx)) {print(foo);}", ctx);
} catch (Exception e) {
e.printStackTrace();
}
try {
// 'with' failure - context was not event bound
eval("print('4th - :('); with(ctx) {print(foo);}", ctx);
} catch (Exception e) {
e.printStackTrace();
}
}
private static void eval(String code, Map<Object, Object> ctx) throws ScriptException {
ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
engine.getContext().setAttribute("ctx", ctx, ScriptContext.ENGINE_SCOPE);
engine.eval(code);
}
}
Thank You for any help.