Chapter 12. Scripting Java

Despite its name, the JavaScript programming language is unrelated to the Java programming language. There is a superficial syntactical resemblance because they both use syntax of the C programming language, but beneath that they are very different. Nevertheless, JavaScript has evolved and can now actually be used to script Java.[*] Java 6 recognizes this fact and ships with a bundled JavaScript interpreter so that scripting capability can easily be embedded into any Java application. Furthermore, some JavaScript interpreters (such as the one bundled with Java 6) support a feature set that allows JavaScript to interact with Java objects, setting and querying fields and invoking methods.

This chapter first explains how to embed a JavaScript interpreter into a Java 6 application and how to run JavaScript scripts from that application. It then turns things around and demonstrates how those scripts can script Java objects directly.

I’ll return to the topic of Java scripting again in Chapter 23, which covers Java applets and the Java plug-in in the context of a web browser.

Embedding JavaScript

We are nearing the end of the Core JavaScript section of this book. Part II of this book is entirely devoted to JavaScript as it is used in web browsers. Before beginning that discussion, however, let’s briefly look at how JavaScript can be embedded into other applications. The motivation for embedding JavaScript within applications is typically to allow users ...

Get JavaScript: The Definitive Guide, 5th Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.