🧠 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:
Feature | Description |
---|---|
Language | JavaScript (ECMAScript 5.1 standard) |
Introduced In | Java 8 (jdk.nashorn.api.scripting ) |
Based On | The JSR 223 scripting API |
Performance | Faster than the old Rhino engine |
Interoperability | Allows calling Java classes and methods from JavaScript |
Deprecated | Since 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 Case | Alternative |
---|---|
JavaScript scripting | GraalVM JavaScript |
General scripting | JSR-223 engines (e.g., Groovy, Kotlin, etc.) |
Polyglot applications | GraalVM (multi-language support) |