Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

There are several questions how to determine the javascript engine in browser. I have to write javascript code that has to run on rhino and nashorn.

How can I determine if my code is running on rhino or nashorn? Are there typcial functions, variables, constants where you can determine the engine?

like image 506
Christian13467 Avatar asked Jun 09 '16 06:06

Christian13467


People also ask

Which JavaScript engine was replaced by Nashorn?

Nashorn is introduced in JDK 8 to replace existing JavaScript engine i.e. Rhino.

Which is replaced with Nashorn?

The Nashorn engine has been deprecated in JDK 11 as part of JEP 335 and and has been removed from JDK15 as part of JEP 372. GraalVM can step in as a replacement for JavaScript code previously executed on the Nashorn engine. GraalVM provides all the features for JavaScript previously provided by Nashorn.

What is the use of Nashorn JavaScript engine?

Nashorn is a JavaScript engine. It is used to execute JavaScript code dynamically at JVM (Java Virtual Machine). Java provides a command-line tool jjs which is used to execute JavaScript code. You can execute JavaScript code by using jjs command-line tool and by embedding into Java source code.

What is the substitute of Rhino JavaScript?

Nashorn was designed to be a better, faster replacement for the old Rhino engine, and by most measures it succeeds.


1 Answers

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

If you're not using the Rhino compatibility script, this would do it:

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

...since importClass is defined for Rhino but not for Nashorn (unless you include the compatibility script).

I think Java.type is Nashorn-specific, so:

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

You could check for wrapping of 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 that will be true for Nashorn but false for Rhino. It does involve throwing an exception, which is unfortunate.

like image 101
T.J. Crowder Avatar answered Sep 21 '22 16:09

T.J. Crowder