JavaScript: The Definitive GuideJavaScript: The Definitive GuideSearch this book

22.7. Java-to-JavaScript Data Conversion

In the last two sections, we discussed the rules by which values are converted when JavaScript reads and writes Java fields and invokes Java methods. Those rules explained how the JavaScript JavaObject, JavaArray, and JavaClass objects convert data; they apply only to the case of JavaScript manipulating Java. When Java manipulates JavaScript, the conversion is performed by the Java JSObject class, and the conversion rules are different. Figure 22-4 and Figure 22-5 illustrate these conversions.

Figure 22-4

Figure 22-4. Data conversions performed when Java writes JavaScript values

Figure 22-5

Figure 22-5. Data conversions performed when Java reads JavaScript values

The point to remember when studying these figures is that Java can interact with JavaScript only through the API provided by the JSObject class. Because Java is a strongly typed language, the methods defined by this class can work only with Java objects, not with primitive values. For example, when you read the value of a JavaScript number, the getMember( ) method returns a java.lang.Double object, rather than a primitive double value.

When writing JavaScript functions that are invoked from Java, bear in mind that the arguments passed by Java are either JavaScript objects from unwrapped Java JSObjects, or JavaObjects. LiveConnect simply does not allow Java to pass primitive values as method arguments. As we saw earlier in this chapter, JavaObject objects behave somewhat differently than other objects. For example, an instance of java.lang.Double behaves differently than a primitive JavaScript number or even a JavaScript Number object. The same caution applies when you are working with JavaScript properties that have their values set by Java.

One way to avoid the whole issue of data conversion is to use the eval( ) method of the JSObject class whenever your Java code wants to communicate with JavaScript. In order to do this, your Java code must convert all method arguments or property values to string form. Then, the string to be evaluated can be passed unchanged to JavaScript, which can convert the string form of the data to the appropriate JavaScript data values.



Library Navigation Links

Copyright © 2003 O'Reilly & Associates. All rights reserved.