Visit Mozilla.org

Core JavaScript 1.5 Guide:LiveConnect Overview:JavaScript to Java Communication

From MDC


Contents

[edit] JavaScript to Java Communication

When you refer to a Java package or class, or work with a Java object or array, you use one of the special LiveConnect objects. All JavaScript access to Java takes place with these objects, which are summarized in the following table.

Object Description
JavaArray A wrapped Java array, accessed from within JavaScript code.
JavaClass A JavaScript reference to a Java class.
JavaObject A wrapped Java object, accessed from within JavaScript code.
JavaPackage A JavaScript reference to a Java package.

Table 9.1 The LiveConnect Objects


Note: Because Java is a strongly typed language and JavaScript is weakly typed, the JavaScript runtime engine converts argument values into the appropriate data types for the other language when you use LiveConnect. See Data Type Conversion for complete information.

In some ways, the existence of the LiveConnect objects is transparent, because you interact with Java in a fairly intuitive way. For example, you can create a Java String object and assign it to the JavaScript variable myString by using the new operator with the Java constructor, as follows:

var myString = new java.lang.String("Hello world")

In the previous example, the variable myString is a JavaObject because it holds an instance of the Java object String. As a JavaObject, myString has access to the public instance methods of java.lang.String and its superclass, java.lang.Object. These Java methods are available in JavaScript as methods of the JavaObject, and you can call them as follows:

myString.length() // returns 11

Static members can be called directly on the JavaClass object.

alert(java.lang.Integer.MAX_VALUE); //alerts 2147483647

[edit] The Packages Object

If a Java class is not part of the java, sun, or netscape packages, you access it with the Packages object. For example, suppose the Redwood corporation uses a Java package called redwood to contain various Java classes that it implements. To create an instance of the HelloWorld class in redwood, you access the constructor of the class as follows:

var red = new Packages.redwood.HelloWorld()

You can also access classes in the default package (that is, classes that don't explicitly name a package). For example, if the HelloWorld class is directly in the CLASSPATH and not in a package, you can access it as follows:

var red = new Packages.HelloWorld()

The LiveConnect java, sun, and netscape objects provide shortcuts for commonly used Java packages. For example, you can use the following:

var myString = new java.lang.String("Hello world")

instead of the longer version:

var myString = new Packages.java.lang.String("Hello world")

[edit] Working with Java Arrays

When any Java method creates an array and you reference that array in JavaScript, you are working with a JavaArray. For example, the following code creates the JavaArray x with ten elements of type int:

x = java.lang.reflect.Array.newInstance(java.lang.Integer, 10)

Like the JavaScript Array object, JavaArray has a length property which returns the number of elements in the array. Unlike Array.length, JavaArray.length is a read-only property, because the number of elements in a Java array are fixed at the time of creation.

[edit] Package and Class References

Simple references to Java packages and classes from JavaScript create the JavaPackage and JavaClass objects. In the earlier example about the Redwood corporation, for example, the reference Packages.redwood is a JavaPackage object. Similarly, a reference such as java.lang.String is a JavaClass object.

Most of the time, you don't have to worry about the JavaPackage and JavaClass objects—you just work with Java packages and classes, and LiveConnect creates these objects transparently.

In JavaScript 1.3 and earlier, JavaClass objects are not automatically converted to instances of java.lang.Class when you pass them as parameters to Java methods—you must create a wrapper around an instance of java.lang.Class. In the following example, the forName method creates a wrapper object theClass, which is then passed to the newInstance method to create an array.

// JavaScript 1.3
theClass = java.lang.Class.forName("java.lang.String")
theArray = java.lang.reflect.Array.newInstance(theClass, 5)

In JavaScript 1.4 and later, you can pass a JavaClass object directly to a method, as shown in the following example:

// JavaScript 1.4
theArray = java.lang.reflect.Array.newInstance(java.lang.String, 5)

[edit] Arguments of Type char

In JavaScript 1.4 and later, you can pass a one-character string to a Java method which requires an argument of type char. For example, you can pass the string "H" to the Character constructor as follows:

c = new java.lang.Character("H")

In JavaScript 1.3 and earlier, you must pass such methods an integer which corresponds to the Unicode value of the character. For example, the following code also assigns the value "H" to the variable c:

c = new java.lang.Character(72)

[edit] Handling Java Exceptions in JavaScript

Note: Due to bug 391642, the ability for try-catch blocks to handle Java exceptions is broken now. The only alternative might be to change the Java code to return a string or an error object upon an exception which could then be tested by Javascript.

When Java code fails at run time, it throws an exception. If your JavaScript code accesses a Java data member or method and fails, the Java exception is passed on to JavaScript for you to handle. Beginning with JavaScript 1.4, you can catch this exception in a try...catch statement.

For example, suppose you are using the Java forName method to assign the name of a Java class to a variable called theClass. The forName method throws an exception if the value you pass it does not evaluate to the name of a Java class. Place the forName assignment statement in a try block to handle the exception, as follows:

function getClass(javaClassName) {
   try {
      var theClass = java.lang.Class.forName(javaClassName);
   } catch (e) {
      return ("The Java exception is " + e);
   }
   return theClass
}

In this example, if javaClassName evaluates to a legal class name, such as "java.lang.String", the assignment succeeds. If javaClassName evaluates to an invalid class name, such as "String", the getClass function catches the exception and returns something similar to the following:

The Java exception is java.lang.ClassNotFoundException: String

For specialized handling based on the exception type, use the instanceof operator:

try {
  // ...
} catch (e) {
  if (e instanceof java.io.FileNotFound) {
     // handling for FileNotFound
  } else {
    throw e;
  }
}

See Exception Handling Statements for more information about JavaScript exceptions.

« Previous Next »