Java Reference
In-Depth Information
You want to utilize JavaScript to implement a portion of your Java application.
Solution
Utilize the Nashorn engine to embed JavaScript in a Java application. The following
example executes inline JavaScript by executing a Nashorn ScriptEngine .
public class Recipe02_12 {
public static void loadInlineJs() {
ScriptEngineManager sem = new
ScriptEngineManager();
ScriptEngine nashorn
= sem.getEngineByName("nashorn");
try {
nashorn.eval("print('This is being printed
with JavaScript');");
} catch (ScriptException ex) {
Logger.getLogger(Recipe02_12.class.getName()).log(Level.SEVERE,
null, ex);
}
}
public static void main(String[] main) {
loadInlineJs();
}
}
How It Works
Nashorn is a new JavaScript engine that has been included in Java 8. To execute
JavaScript within a Java application, you invoke an instance of the Nashorn engine,
passing it to the engine inline or external JavaScript. In this recipe, the Nashorn engine
is obtained by calling on the ScriptEngineManager and passing "nashorn" as
the argument. After obtaining the Nashorn engine, you are ready to invoke a JavaScript
Search WWH ::




Custom Search