How to determine which javascript engine, rhino or nashorn is running my code?

There are several questions about how to determine the JavaScript engine in a browser. I need to write javascript code that should work on rhino and horseback.

How to determine if my code works on rhino or nashorn? Are there typical functions, variables, constants where you can define an engine?

+5
source share
2 answers

Looking at the Rhino to Nashorn porting guide , I see several possible ways.

If you are not using compatibility with the Rhino script, this would do this:

var usingNashorn = typeof importClass !== "function"; 

... since importClass is defined for Rhino, but not for Nashorn (unless you have enabled script compatibility).

I think Java.type is specific to Nashorn, therefore:

 var usingNashorn = typeof Java !== "undefined" && Java && typeof Java.type === "function"; 

You can check for exceptions:

 var usingNashorn; try { // Anything that will throw an NPE from the Java layer java.lang.System.loadLibrary(null); } catch (e) { // false! usingNashorn = e instanceof java.lang.NullPointerException; } 

... since the migration guide says it will be true for Nashorn, but false for Rhino. This is because you selected an exception, which is unsuccessful.

+1
source

With the --no-java parameter, Java is not defined as an object in Nashorn. It would be best to check out what is always available in Nashorn. A good candidate is something like a DIR or FILE variable. Always up there.

jjs> typeof DIR

line

If you use the javax.script API (and not jjs), you can get the engine name and check also:

 import javax.script.*; public class Main { public static void main(String[] args) throws Exception { ScriptEngineManager m = new ScriptEngineManager(); ScriptEngine e = m.getEngineByName("nashorn"); System.out.println(e.getFactory().getEngineName()); } } 

With Nashorn, you will see "Oracle Nashorn" as the name of the engine.

+1
source

All Articles