Skip to content Skip to sidebar Skip to footer

Access Variable Of Scriptcontext Using Nashorn Javascript Engine (java 8)

I used the following code with the Rhino JavaScript engine in Java: @Test public void testRhino() throws ScriptException { final ScriptEngineManager factory = new ScriptEngineM

Solution 1:

If you use ScriptEngine.createEngine API to create ENGINE_SCOPE Bindings, it'll work as expected:

import javax.script.*;

publicclassMain {
  publicstaticvoidmain(String[] args)throws Exception {

    finalScriptEngineManagerfactory=newScriptEngineManager();
    finalScriptEngineengine= factory.getEngineByName("nashorn");
    finalStringraw="I am the raw value injected";
    finalScriptContextctx=newSimpleScriptContext();

    // **This is the inserted line**
    ctx.setBindings(engine.createBindings(), ScriptContext.ENGINE_SCOPE);

    ctx.setAttribute("raw", raw, ScriptContext.ENGINE_SCOPE);

    Stringscript="var result = 'I am a result';";
    script += "java.lang.System.out.println(raw);";
    script += "'I am a returned value';";

    finalObjectres= engine.eval(script, ctx);
    System.out.println(ctx.getAttribute("result"));
    System.out.println(res);
 }
}

Solution 2:

Nashorn treats the Bindings stored in ScriptContext as "read-only". Any attempt to set a variable stored in a Bindings object (or to create a new variable) will result in a new variable being created in nashorn.global which shadows the Bindings parameter by that name.

You can use the engine to "evaluate" the variable, using this code:

System.out.println( engine.eval("result", ctx) );

This is, however, quite ugly. "result" is first compiled into a script, and then that script is evaluated, to return the variable's value. Fine for testing, but perhaps a little too inefficient for a general solution.

A better, but perhaps more fragile method, is to extract the "nashorn.global" variable, and query it for the desired value.

Bindings nashorn_global = (Bindings) ctx.getAttribute("nashorn.global");
System.out.println( nashorn_global.get("result") );

See also my hack/answer in Capturing Nashorn's Global Variables for automated way of moving nashorn.global values back to a Map<String,Object> after evaluating a script.

Post a Comment for "Access Variable Of Scriptcontext Using Nashorn Javascript Engine (java 8)"