Using Java Classes Directly
As described in the previous two sections, both Netscape and Internet Explorer allow JavaScript code to interact with Java applets and Java applets to interact with JavaScript. Netscape’s LiveConnect technology also allows JavaScript programs to instantiate their own Java objects and use them, even in the absence of any applets. Internet Explorer does not have any analogous capability.
In Netscape, the
Packages
object provides access to all the
Java packages that Netscape knows about. The expression
Packages.java.lang
refers to the
java.lang package, and the expression
Packages.java.lang.System
refers to the
java.lang.System class. For convenience,
java
is a shortcut for
Packages.java
. In Netscape, JavaScript code might
invoke a static method of this java.lang.System
class as follows:
// Invoke the static Java method System.getProperty( ) var javaVersion = java.lang.System.getProperty("java.version");
This use of LiveConnect is not limited to system classes, because
LiveConnect allows us to use the JavaScript new
operator to create new instances of Java classes (just as we would in
Java). Example 22-2 shows JavaScript code that uses
standard Java classes (the JavaScript code looks almost identical to
Java code, in fact) to pop up a window and display some text. The
result is shown in Figure 22-1.
Figure 22-1. A Java window created from JavaScript
Example 22-2. Scripting ...
Get JavaScript: The Definitive Guide, Fourth Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.