How do I initialize the Nashorn context and engine directly?

I am trying to initialize Oracle javascript nashorn engine directy from namespace jdk.nashorn.*

. (nashorn library - 2013 beta).

There is a web sample that calls an instance of the Nashorn engine using the javax.script.ScriptEngineManager utility class.

var engine = ScriptEngineManager.getEngineByName(*)

      

However, I like to stay away from the ScriptEngineManager, so I need to call the engine directly in the same way that Rhino can.

Context cx = Context.enter();
Scriptable scope = cx.initStandardObjects();

      

How can I instantiate the nashorn engine directly?

+3


source to share


2 answers


javax script engine by type application / javascript Hashorn, return the script engine and tell it to do something, it also provides invokable and compilable interfaces.

Yout might be interested to read the following: How can I start coding with Oracle Nashorn JS Engine and when will it replace Rhino in OpenJDK?



Usage example:

import javax.*; //lib imports
// we should use the javax.script API for Nahsorn
ScriptEngineManager m = new ScripteEngineManager(); 
ScriptEngine e = m.getEngineByname("nashorn");
try {
   e.eval("print('hello nashorn !')");
} catch(Exception e) {
  // using jdk lower then version 8 maybe ?
}

      

+3


source


I found a way to start the engine directly using .NET without

    "javax.script.ScriptEngineManager"

      

Environment: IKVM.NET Version 8 + .NET Framework 4.52



    static void Main(string[] args)
    {

        jdk.nashorn.api.scripting.NashornScriptEngineFactory fact = new jdk.nashorn.api.scripting.NashornScriptEngineFactory();
        jdk.nashorn.api.scripting.NashornScriptEngine nashornengine = fact.getScriptEngine() as jdk.nashorn.api.scripting.NashornScriptEngine;

        nashornengine.eval("var x = 1/3;");
        object result = nashornengine.get("x");
        Console.WriteLine("{0}", result);
    }

      

This allows me to directly interact with nashorn context methods directly.

 compile()
 getFactory()
 invokeMethod()
 invokeFunction()

      

+1


source







All Articles