Java Reference
In-Depth Information
In Nashorn, the print() function prints a message on the standard output and
a string literal is a sequence of characters enclosed in single or double quotes. The
following snippet of code stores a script in a String object that prints Hello Scripting!
on the standard output:
// Store a Nashorn script in a string
String script = "print('Hello Scripting!')";
If you want to use double quotes to enclose the string literal in Nashorn, the
statement will look as shown:
// Store a Nashorn script in a string
String script = "print(\"Hello Scripting!\")";
To execute the script, you need to pass it to the eval() method of the script engine.
A script engine may throw a ScriptException when it runs a script. For this reason, you
need to handle this exception when you call the eval() method of the ScriptEngine . The
following snippet of code executes the script stored in the script variable:
try {
engine.eval(script);
}
catch (ScriptException e) {
e.printStackTrace();
}
Listing 1-1 contains the complete code for the program to print a message on the
standard output.
Listing 1-1. Printing a Message on the Standard Output Using Nashorn
// HelloScripting.java
package com.jdojo.script;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
public class HelloScripting {
public static void main(String[] args) {
// Create a script engine manager
ScriptEngineManager manager = new ScriptEngineManager();
// Obtain a Nashorn script engine from the manager
ScriptEngine engine = manager.getEngineByName("JavaScript");
// Store the script in a String
String script = "print('Hello Scripting!')";
 
Search WWH ::




Custom Search