Calling Java Methods from JavaScript


JavaScript can now refer to Java packages, classes, and objects. Once references to these objects have been obtained, they can be used just as they are in Java code.

Access to Java Packages and Classes

The top level of the Java package namespace appears in JavaScript under the name 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

Access to Applets and Plugin objects

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