Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống
1
/ 372 trang
THÔNG TIN TÀI LIỆU
Cấu trúc
Contents at a Glance
Contents
About the Author
About the Technical Reviewers
Acknowledgments
Introduction
Chapter 1: Getting Started
What Is Scripting in Java?
Executing Your First Script
Using the jjs Command-line Tool
Printing Text in Nashorn
Using Other Scripting Languages
Exploring the javax.script Package
The ScriptEngine and ScriptEngineFactory Interfaces
The AbstractScriptEngine Class
The ScriptEngineManager Class
The Compilable Interface and the CompiledScript Class
The Invocable Interface
The Bindings Interface and the SimpleBindings Class
The ScriptContext Interface and the SimpleScriptContext Class
The ScriptException Class
Discovering and Instantiating ScriptEngines
Summary
Chapter 2: Executing Scripts
Using the eval( ) Method
Passing Parameters
Passing Parameters from Java Code to Scripts
Passing Parameters from Scripts to Java Code
Summary
Chapter 3: Passing Parameters to Scripts
Bindings, Scope, and Context
Bindings
Scope
Defining the Script Context
Putting Them Together
Using a Custom ScriptContext
Return Value of the eval( ) Method
Reserved Keys for Engine Scope Bindings
Changing the Default ScriptContext
Sending Scripts Output to a File
Summary
Chapter 4: Writing Scripts in Nashorn
Strict and Nonstrict Modes
Identifiers
Comments
Declaring Variables
Data Types
The Undefined Type
The Null Type
The Number Type
The Boolean Type
The String Type
Operators
Type Conversion
To Boolean Conversion
To Number Conversion
To String Conversion
Statements
Block Statement
Variable Statement
Empty Statement
Expression Statement
The if Statement
Iteration Statements
The continue, break, and return Statements
The with Statement
The switch Statement
Labelled Statements
The throw Statement
The try Statement
The debugger Statement
Defining Functions
Function Declaration
Working with Function Arguments
Function Expression
The Function( ) Constructor
The Object Type
Using an Object Literal
Accessing Object’s Properties
Defining Accessor Properties
Setting Property Attributes
Deleting Properties of an Object
Using a Constructor Function
Object Inheritance
Using Object.create( ) Method
Binding Object Properties
Locking Objects
Accessing Missing Properties
Serializing Objects
Dynamically Evaluating Scripts
Variable Scoping and Hoisting
Using Strict Mode
Built-in Global Objects
The Object Object
The Function Object
The String Object
The Number Object
The Boolean Object
The Date Object
The Math Object
The RegExp Object
Knowing Script Location
Built-in Global Functions
The parseInt( ) Function
The parseFloat() Function
The isNaN() Function
The isFinite( ) Function
The decodeURI( ) Function
The decodeURIComponent( ) Function
The encodeURI( ) Function
The encodeURIComponent() Function
The load( ) and loadWithNewGlobal Functions
Summary
Chapter 5: Procedures and Compiled Scripts
Invoking Procedures in Scripts
Implementing Java Interfaces in Scripts
Using Compiled Scripts
Summary
Chapter 6: Using Java in Scripting Languages
Importing Java Types
Using the Packages Global Object
Using the Java Global Object
Using the importPackage() and importClass() Functions
Using the JavaImporter Object
Creating and Using Java Objects
Using Overloaded Java Methods
Using Java Arrays
Extending Java Classes Implementing Interfaces
Using a Script Object
Using the Anonymous Class–Like Syntax
Using the JavaAdapter Object
Using the Java.extend() Method
Using a JavaScript Function
Accessing Methods of a Superclass
Using Lambda Expressions
Summary
Chapter 7: Collections
What Is an Array in Nashorn?
Creating an Array
Using an Array Literal
Using the Array Object
Passing No Arguments
Passing One Argument
Passing Two or More Arguments
Deleting Array Elements
Length of an Array
Iterating Over Array Elements
Using the for Loop
Using the forEach() Method
Using the for-in Loop
Checking for an Array
Multidimensional Arrays
Methods of the Array Object
Concatenating Elements
Joining Array Elements
Reversing Array Elements
Slicing an Array
Splicing an Array
Sorting an Array
Adding and Removing Elements at Ends
Searching an Array
Evaluating Predicates
Converting an Array to a String
Stream-Like Processing of Arrays
Array-Like Objects
Typed Arrays
The ArrayBuffer Object
Views of an ArrayBuffer
Typed Arrays
DataView View
Using Lists, Maps, and Sets
Using a Java List as a Nashorn Array
Using a Java Map as a Nashorn Object
Using Java Arrays
Arrays to Java Collections Conversions
Summary
Chapter 8: Implementing a Script Engine
Introduction
The Expression Class
The Instance Variables
The Constructor
The parse() Method
The getOperandValue() Method
The eval() Method
The JKScriptEngine Class
The JKScriptEngineFactory Class
Preparing for Deployment
Packaging the JKScript Files
Using the JKScript Script Engine
Summary
Chapter 9: The jrunscript Command-Line Shell
The Syntax
Execution Modes of the Shell
One-liner Mode
Batch Mode
Interactive Mode
Listing Available Script Engines
Adding a Script Engine to the Shell
Using Other Script Engines
Passing Arguments to Scripts
Global Functions
Summary
Chapter 10: The jjs Command-Line Tool
The Syntax
The Options
Using jjs in Interactive Mode
Passing Arguments to jjs
Using jjs in Scripting Mode
Summary
Chapter 11: Using JavaFX in Nashorn
JavaFX Support in jjs
Structure of JavaFX Applications in Scripts
Importing JavaFX Types
Summary
Chapter 12: Java APIs for Nashorn
What Are Java APIs for Nashorn?
Instantiating the Nashorn Engine
Sharing the Engine Globals
Using Script Objects in Java Code
Using Properties of Script Objects
Creating Nashorn Objects in Java
Invoking Script Functions From Java
Converting Script Dates to Java Dates
Summary
Chapter 13: Debugging, Tracing, and Profiling Scripts
Debugging Standalone Scripts
Debugging Scripts from Java Code
Tracing and Profiling Scripts
Summary
Index
Nội dung
www.it-ebooks.info For your convenience Apress has placed some of the front matter material after the index Please use the Bookmarks and Contents at a Glance links to access them www.it-ebooks.info Contents at a Glance About the Author��������������������������������������������������������������������������� xvii About the Technical Reviewers������������������������������������������������������ xix Acknowledgments�������������������������������������������������������������������������� xxi Introduction���������������������������������������������������������������������������������� xxiii ■■Chapter 1: Getting Started�������������������������������������������������������������� ■■Chapter 2: Executing Scripts�������������������������������������������������������� 17 ■■Chapter 3: Passing Parameters to Scripts������������������������������������ 25 ■■Chapter 4: Writing Scripts in Nashorn������������������������������������������ 51 ■■Chapter 5: Procedures and Compiled Scripts����������������������������� 175 ■■Chapter 6: Using JavainScripting Languages��������������������������� 191 ■■Chapter 7: Collections���������������������������������������������������������������� 211 ■■Chapter 8: Implementing a Script Engine����������������������������������� 263 ■■Chapter 9: The jrunscript Command-Line Shell�������������������������� 281 ■■Chapter 10: The jjs Command-Line Tool������������������������������������� 295 ■■Chapter 11: Using JavaFX in Nashorn���������������������������������������� 307 ■■Chapter 12: Java APIs for Nashorn�������������������������������������������� 319 ■■Chapter 13: Debugging, Tracing, and Profiling Scripts��������������� 343 Index���������������������������������������������������������������������������������������������� 355 v www.it-ebooks.info Introduction When I wrote the three volumes of Harnessing Javain 2012, I did not include a chapter on the JavaScripting API because of the limited space that I had for each volume Note the phrase “Java Scripting,” which uses two separate words: “Java” and “Scripting.” “JavaScript” is the name of a scripting language, which has nothing to with the Java programming language, whereas the phrase “Java Scripting API” is the Java API that lets Java applications interact with scripting languages In the first release, I had titled this book Harnessing Scriptingin Java, and it covered only the JavaScripting API and Rhino script engine The release did not cover the JavaScript language JDK ships with a lightweight high-performance JavaScript engine called Nashorn, which replaces the Rhino engine that shipped with JDK7 This book covers the JavaScript language completely with comprehensive coverage of the Nashorn engine Learning the JavaScripting API, which was introduced inJava 6, is not essential for all Java developers, although it is important and very useful if you are familiar with scripting languages such as Rhino JavaScript, Groovy, Jython, JRuby, and so on and want to take advantage of those scripting languages inJava applications I started learning the JavaScripting API by reading some online blogs and articles; they were helpful, but not quite comprehensive in giving me a clear and complete picture of how the JavaScripting API helps Java applications interact with scripting languages My next step in the learning process was reading the specification for JSR-223, Scripting for the Java Platform Specification, along with the Java API documentation for the javax.script package Reading the JSR-233 specification gave me a complete picture of the JavaScripting API; however, I was not ready to write this book I was still missing some pieces of the puzzle Therefore, I decided to read the source code for the classes in the javax.script package I also read the source code for some scripting languages Finally, in the process of learning the API, I developed a simple scripting engine, which I named JKScript Finally, I read the ECMAScript 5.1 specification to get a complete picture of the JavaScript language itself The main difficulty that I faced in writing this book was getting the information on the Nashorn engine and its features A Wiki is maintained at https://wiki.openjdk.java.net/display/Nashorn/Main, which provides information about the Nashorn engine in bits and pieces Tying them together in this book with cohesive examples was a challenge It is my sincere hope that readers will enjoy this book and benefit from it xxiii www.it-ebooks.info ■ Introduction Structure of the Book This book contains 13 chapters: Each chapter introduces a new topic from the JavaScripting API and the JavaScript language Each chapter makes use of the material covered in the previous chapters Chapter 1, Getting Started, introduces you to the JavaScripting API and demonstrates how to write your first Java program to execute a script written in Nashorn It walks through the steps that are needed to download and install other scripting languages such as Groovy, Jython, and JRuby Finally, this chapter takes a brief tour of the classes and interfaces contained in the javax.script package, describing their usages and relationship with other classes Chapter 2, Executing Scripts, shows how to execute a script, which is stored in a file It also demonstrates how to pass parameters from a Java application to a scripting engine, and vice versa Chapter 3, Passing Parameter to Scripts, discusses advanced techniques and all the internal setups that are involved in passing parameters between a Java application and a scripting engine It starts with a detailed description of the terms binding, scope, and script context Later, it explains in detail with several illustrations how bindings, scope, and script context work together in the JavaScripting API Each explanation is paired with a snippet of code, a complete program, or both The chapter ends with a program that shows how to redirect outputs from a script to a file Chapter 4, Writing Scripts in Nashorn, covers the JavaScript language in great detail as described in the ECMAScript 5.1 specification that is supported by the Nashorn engine Chapter 5, Procedures and Compiled Scripts, explains how to invoke top-level procedures, functions, and object-level methods written in a scripting language from a Java application It explains how to compile scripts in intermediate form, if supported by the scripting engine, and execute them repeatedly Chapter 6, Using Javain Nashorn, explains how to use features and constructs of the Java programming language inside scripting languages The Java features discussed are importing Java classes, creating Java objects, using Java overloaded methods, implementing Java interfaces, and so on Chapter 7, Collections, explains untyped and typed arrays in Nashorn It also explains how to use Java collection classes such as java.util.Set and java.util.Map in Nashorn Chapter 8, Implementing a Script Engine, discusses the steps needed to implement a new script engine It explains all classes and interfaces in the JavaScripting API that are involved in creating a new script engine It walks through the deployment setup that makes a script engine autodiscoverable by a script engine manager In the process, it creates a simple script engine, which we call JKScript, which is capable of executing an arithmetic expression Chapter 9, The jrunscript Command-Line Shell, explains how to use the jrunscript command-line shell to execute script using different scripting engines Chapter 10, The jjs Command-Line Tool, explains how to use the jjs command-line tool to execute Nashorn scripts in different modes It walks through the syntax and the options for the command-line tool Several examples are provided to illustrate the usage of the shell xxiv www.it-ebooks.info ■ Introduction Chapter 11, Using JavaFX in Nashorn, explains how to write and run JavaFX programs using the jjs command-line tool Chapter 12, Java APIs for Nashorn, covers the Java classes and interfaces that can be used to work with JavaScript objects inJava programs Chapter 13, Debugging, Tracing, and Profiling Scripts, explains the debugging support in NetBeans 8.0 for debugging Nashorn scripts It also explains how to trace and profile Nashorn scripts Audience This book is designed to be useful for anyone who wants to learn the JavaScripting API inJava and Nashorn JavaScript A basic knowledge of Java is required to use this book Although it would be helpful to have a prior knowledge of a scripting language such as Rhino JavaScript, Groovy, JRuby, Jython, and so on, it is not required Examples contained in this book are written in Nashorn JavaScript Examples are deliberately kept simple and short so that readers can understand them without any prior experience with a scripting language If you not have experience working with a scripting language, you need to read the book chapter-by-chapter sequentially Source Code and Errata Source code and errata for this book may be downloaded from www.apress.com/source-code Questions and Comments Please direct all your questions and comments for the author to ksharan@jdojo.com xxv www.it-ebooks.info Chapter Getting Started In this chapter, you will learn: • What scriptinginJava is • How to execute your first script from Java • How to use other scripting languages such as JRuby, Jython from Java • javax.script API • How script engines are discovered and instantiated What Is Scriptingin Java? Some believe that the Java Virtual Machine (JVM) can execute programs written only in the Java programming language However, that is not true The JVM executes languageneutral bytecode It can execute programs written in any programming language, if the program can be compiled into Java bytecode A scripting language is a programming language that provides you with the ability to write scripts that are evaluated (or interpreted) by a runtime environment called a script engine (or an interpreter) A script is a sequence of characters that is written using the syntax of a scripting language and used as the source for a program executed by an interpreter The interpreter parses the scripts, produces intermediate code, which is an internal representation of the program, and executes the intermediate code The interpreter stores the variables used in a script in data structures called symbol tables Typically, unlike in a compiled programming language, the source code (called a script) in a scripting language is not compiled but is interpreted at runtime However, scripts written in some scripting languages may be compiled into Java bytecode that can be run by the JVM Java added scripting support to the Java platform that lets a Java application execute scripts written inscripting languages such as Rhino JavaScript, Groovy, Jython, JRuby, Nashorn JavaScript, and so on Two-way communication is supported It also lets scripts access Java objects created by the host application The Java runtime and a scripting language runtime can communicate and make use of each other’s features Support for scripting languages inJava comes through the JavaScripting API All classes and interfaces in the JavaScripting API are in the javax.script package www.it-ebooks.info Chapter ■ Getting Started Using a scripting language in a Java application provides several advantages: • Most scripting languages are dynamically typed, which makes it simpler to write programs • They provide a quicker way to develop and test small applications • Customization by end users is possible • A scripting language may provide domain-specific features that are not available inJavaScripting languages have some disadvantages as well For example, dynamic typing is good to write simpler code; however, it turns into a disadvantage when a type is interpreted incorrectly and you have to spend a lot of time debugging it Scripting support inJava lets you take advantage of both worlds: it allows you to use the Java programming language for developing statically typed, scalable, and high-performance parts of the application and use a scripting language that fits the domain-specific needs for other parts I will use the term script engine frequently in this book A script engine is a software component that executes programs written in a particular scripting language Typically, but not necessarily, a script engine is an implementation of an interpreter for a scripting language Interpreters for several scripting languages have been implemented inJava They expose programming interfaces so a Java program may interact with them JDK was cobundled with a script engine called Rhino JavaScript JDK replaced the Rhino JavaScript engine with a lightweight, faster script engine called Nashorn JavaScript This book discusses Nashorn JavaScript, not Rhino JavaScript Please visit www.mozilla.org/rhino for more details on Rhino JavaScript documentation If you want to migrate programs written with Rhino JavaScript to Nashorn, please visit the Rhino Migration Guide at https://wiki.openjdk.java.net/display/Nashorn/Rhino+Migration+Guide If you are interested in using Rhino JavaScript with JDK 8, visit the page at https://wiki.openjdk.java.net/display/Nashorn/Using+Rhino+JSR-223+engine+with+JDK8 Java includes a command-line shell called jrunscript that can be used to run scripts in an interactive mode or a batch mode The jrunscript shell is scriptinglanguage-neutral; the default language is Rhino JavaScript in JDK and Nashorn in JDK I will discuss the jrunscript shell in detail in Chapter JDK includes another command-line tool called jjs that invokes the Nashorn engine and offers Nashorn-specific command-line options If you are using Nashorn, you should use the jjs command-line tool over jrunscript I will discuss the jjs command-line tool in Chapter 10 Java can execute scripts in any scripting language that provides an implementation for a script engine For example, Java can execute scripts written in Nashorn JavaScript, Rhino JavaScript, Groovy, Jython, JRuby, and so on Examples in this book use Nashorn JavaScript language In this book, the terms “Nashorn,” “Nashorn Engine,” “Nashorn JavaScript,” “Nashorn JavaScript Engine,” “Nashorn Scripting Language,” and “JavaScript” have been used synonymously www.it-ebooks.info Chapter ■ Getting Started The Nashorn scripting engine can be invoked in two ways: • By embedding the engine in the JVM • By using the jjs command-line tool In this chapter, I will discuss both ways of using the Nashorn script engine Executing Your First Script In this section, you will use Nashorn to print a message on the standard output You will access the Nashorn engine from Java code The same steps can be used to print a message using any other scripting languages, with one difference: you will need to use the scripting language-specific code to print the message You need to perform three steps to run a script in Java: • Create a script engine manager • Get an instance of a script engine from the script engine manager • Call the eval() method of the script engine to execute a script A script engine manager is an instance of the ScriptEngineManager class You can create a script engine, like so: // Create a script engine manager ScriptEngineManager manager = new ScriptEngineManager(); An instance of the ScriptEngine interface represents a script engine in a Java program The getEngineByName(String engineShortName) method of a ScriptEngineManager is used to get an instance of a script engine To get an instance of the Nashorn engine, use JavaScript as the short name of the engine as shown: // Get the reference of a Nashorn engine ScriptEngine engine = manager.getEngineByName("JavaScript"); ■■Tip The short name of a script engine is case-sensitive Sometimes a script engine has multiple short names Nashorn engine has the following short names: nashorn, Nashorn, js, JS, JavaScript, javascript, ECMAScript, ecmascript You can use any of the short names of an engine to get its instance using the getEngineByName() method of the ScriptEngineManager class www.it-ebooks.info Chapter ■ Getting Started 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!')"; www.it-ebooks.info ... for scripting languages in Java comes through the Java Scripting API All classes and interfaces in the Java Scripting API are in the javax.script package www.it-ebooks.info Chapter ■ Getting... Java applications interact with scripting languages In the first release, I had titled this book Harnessing Scripting in Java, and it covered only the Java Scripting API and Rhino script engine... interfaces in the Java Scripting API Figure 1-1. The class diagram for classes and interfaces in the Java Scripting API The ScriptEngine and ScriptEngineFactory Interfaces The ScriptEngine interface