Java Reference
In-Depth Information
You want to load and execute JavaScript code from within your Java application.
Solution
Execute the JavaScript using the Nashorn engine, the next-generation JavaScript en-
gine that is part of Java 8 and is used to execute JavaScript code. The Nashorn engine
can be called upon to process in-line JavaScript, or an external JavaScript file directly
within Java code. Execute an external JavaScript file or in-line JavaScript code using
the Java ScriptEngineManager. Once you've obtained a ScriptEngineMan-
ager() , you get an instance of the Nashorn engine to use for JavaScript code execu-
tion.
In the following example, a Nashorn ScriptEngine is used to invoke a
JavaScript file that resides on the local file system.
public static void loadExternalJs(){
ScriptEngineManager sem = new ScriptEngineManager();
ScriptEngine nashorn = sem.getEngineByName("nashorn");
try {
nashorn.eval("load('src/org/java8recipes/
chapter18/js/helloNashorn.js')");
} catch (ScriptException ex) {
Logger.getLogger(NashornInvoker.class.getName()).log(Level.SEVERE,
null, ex);
}
}
The code that resides in the helloNashorn.js file is as follows:
print("Hello Nashorn!");
Next, let's take a look at some in-line JavaScript. In the following example, a
Nashorn ScriptEngine is obtained, and then a JavaScript function is created for obtain-
ing the gallons of water for an in-ground pool. The function is then executed to return a
result.
public static void loadInlineJs(){
ScriptEngineManager sem = new ScriptEngineManager();
ScriptEngine nashorn = sem.getEngineByName("nashorn");
Search WWH ::




Custom Search