Packages. For
convenience, the names java, sun, and
netscape are defined as aliases for
Packages.java, Packages.sun, and
Packages.netscape respectively. Thus,
you can refer to the Java class java.lang.System as
Packages.java.lang.System or just
java.lang.System. Once you have a reference to
this class, you can access fields and methods with the same syntax
that you would use in Java. For example, the following JavaScript
code will print a message to the Java console:
var System = java.lang.System;
System.err.println("Greetings from JavaScript");
Here, we have set up the variable System to refer to the class
java.lang.System, and then we can get the static field
err from it to get an instance of class
PrintStream. This class supports the method
println which expects a java.lang.String
argument: the JavaScript string is converted to a
java.lang.String automatically by the call to
println.
example of using a java class as a constructor
Packages provides one window into Java from JavaScript.
The other way to reach Java objects is through <APPLET>
and <EMBED> tags that are in the same page as the
JavaScript code. These obey the usual rules for JavaScript access
to HTML tags: if the tag has a NAME attribute you can
access it using that name from the JavaScript document
object. They also show up in the predefined arrays
document.applets and document.embeds. For
example, if you define an applet named myapplet like so:
<APPLET CODE="MyApplet.class" WIDTH=50 HEIGHT=30 NAME=myapplet>
...
</APPLET>
then you can reach the Java object of class MyApplet from
JavaScript as either document.myapplet or
document.applets[0] (for the first applet on the page).
For EMBED tags, the objects available through
document.embeds will be useless dummy objects unless
the plugin is associated with a java class as described in
Section 2.
example of getclass to reach static methods