Search code examples
javascriptjavanashorn

Jdk nashorn api ScriptEngine returning undefined


I am trying to run a simple javascript function using jdk nashorn script engine. There I am returning one of the passed variable to the function just for simplicity to check if nashorn api working fine or not. After script engine runs the function I get undefined as result.

    import jdk.nashorn.api.scripting.ScriptObjectMirror;
    import javax.script.ScriptException;
    import javax.script.Bindings;
    import javax.script.ScriptEngine;
    import jdk.nashorn.api.scripting.NashornScriptEngineFactory;

    public class JDKNashornScriptRunner {

    protected static final ScriptEngine scriptEngine = new NashornScriptEngineFactory().getScriptEngine();
    protected final Bindings bindings;

    public JDKNashornScriptRunner(String script)
    {
        bindings = scriptEngine.createBindings();
        try
        {
            scriptEngine.eval(script, bindings);
        }
        catch( ScriptException e )
        {
            throw new RuntimeException("Exception while compiling script", e);
        }
    }

    public Object runScript( String v1, String v2, String v3, String v4)
            throws NoSuchMethodException, ScriptException
    {
        bindings.clear();
        bindings.put("v1", v1);
        bindings.put("v2", v2);
        bindings.put("v3", v3);
        bindings.put("v4", v4);

        return ((ScriptObjectMirror) bindings.get("myFunction")).call(null);
    }
  }

Main program here -

public class RunMyFunctionScript {
    public static void main(String args[])
    {
        String runScript = "function myFunction(v1, v2, v3, v4) {return v3;}";
        JDKNashornScriptRunner scriptRunner = new JDKNashornScriptRunner(runScript);
        Object result = scriptRunner.runScript("a","b","c","d"); //Here I am getting undefined as value
        String v3Value = String.valueOf(result);
        System.out.println(v3Value);
    }
}

So the problem here is when scriptEngine is trying to run the script using below given line, I am getting undefined (it should give me c as value)

((ScriptObjectMirror) bindings.get("myFunction")).call(null);

Solution

  • Because you're not passing any argument to your JavaScript function. runScript should be:

    public Object runScript( String v1, String v2, String v3, String v4)
            throws NoSuchMethodException, ScriptException
    {
        return ((JSObject) bindings.get("myFunction")).call(null, v1, v2, v3, v4);
    }