Java Language Nashorn JavaScript engine

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Introduction

Nashorn is a JavaScript engine developed in Java by Oracle, and has been released with Java 8. Nashorn allows embedding Javascript in Java applications via JSR-223 and allows to develop standalone Javascript applications, and it provides better runtime performance and better compliance with the ECMA normalized Javascript specification.

Syntax

  • ScriptEngineManager // Provides a discovery and installation mechanism for ScriptEngine classes; uses a SPI (Service Provider Interface)
  • ScriptEngineManager.ScriptEngineManager() // Recommended constructor
  • ScriptEngine // Provides the interface to the scripting language
  • ScriptEngine ScriptEngineManager.getEngineByName(String shortName) // Factory method for the given implementation
  • Object ScriptEngine.eval(String script) // Executes the specified script
  • Object ScriptEngine.eval(Reader reader) // Loads and then executes a script from the specified source
  • ScriptContext ScriptEngine.getContext() // Returns the default bindings, readers and writers provider
  • void ScriptContext.setWriter(Writer writer) // Sets the destination to send script output to

Remarks

Nashorn is a JavaScript engine written in Java and included in Java 8. Everything you need is bundled in the javax.script package.

Note that the ScriptEngineManager provides a generic API allowing you to obtain script engines for various scripting languages (i.e. not only Nashorn, not only JavaScript).



Got any Java Language Question?