Java.Java8.What is Nashorn?

🧠 What is Nashorn?

Nashorn is a JavaScript engine built into the Java 8 platform.

It allows you to run JavaScript code inside a Java application.


🔹 Key Points:

FeatureDescription
LanguageJavaScript (ECMAScript 5.1 standard)
Introduced InJava 8 (jdk.nashorn.api.scripting)
Based OnThe JSR 223 scripting API
PerformanceFaster than the old Rhino engine
InteroperabilityAllows calling Java classes and methods from JavaScript
DeprecatedSince Java 11, and removed in Java 15 (in favor of GraalVM etc.)

✅ Basic Example: Run JavaScript from Java

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;

public class NashornExample {
    public static void main(String[] args) throws Exception {
        ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
        engine.eval("print('Hello from JavaScript!');");
    }
}

🔹 Output:

Hello from JavaScript!

✅ Call Java from JavaScript

engine.eval("var list = new java.util.ArrayList(); list.add('hello'); print(list.get(0));");

🔥 Use Cases (Back in the Day)

  • Embedding scripting support in Java apps
  • Dynamic configuration or plugins
  • Executing user-defined scripts safely (sandboxed)

❌ Why It’s Deprecated

  • JavaScript evolved quickly (ES6, ES7, etc.)
  • Nashorn couldn’t keep up
  • Replaced by modern solutions like GraalVM, which support modern JS

✅ Alternatives Now

Use CaseAlternative
JavaScript scriptingGraalVM JavaScript
General scriptingJSR-223 engines (e.g., Groovy, Kotlin, etc.)
Polyglot applicationsGraalVM (multi-language support)
This entry was posted in Без рубрики. Bookmark the permalink.

Leave a Reply

Your email address will not be published.