Java to JavaScript values (Definition)

Conversion of Java primitives and objects to JavaScript compatible types.

When a Java method returns a value to JavaScript, the Java values need to be converted to compatible and useful data types. This is accomplished with LiveConnect in Netscape Navigator and ActiveX in MSIE.

In some cases a single Java primitive data type will be compatible with JavaScript primitives and objects of many different types. An example of this is the JavaScript Number primitive that will readily accept half a dozen different Java numeric and logical types.

Some Java data types correspond exactly to a single and specific JavaScript type. Examples of this are null, Boolean and void.

A third possibility is that many different Java object types will become a single JavaScript object type. In fact Java objects all become a generic JavaObject.

Here is a table that summarises the correspondence between Java and JavaScript types when converting to Java. This would be used when passing values into methods under control of JavaScript:

booleanboolean primitive
bytenumber primitive
charnumber primitive
doublenumber primitive
floatnumber primitive
intnumber primitive
longnumber primitive
shortnumber primitive
java.lang.BooleanJavaObject object
java.lang.CharacterJavaObject object
java.lang.ClassJavaObject object
java.lang.DoubleJavaObject object
java.lang.FloatJavaObject object
java.lang.IntegerJavaObject object
java.lang.LongJavaObject object
java.lang.StringJavaObject object
All Java arrays regardless of what they containJavaArray
netscape.javascript.JSObjectgeneric JavaScript object
All other Java objectsJavaObject object

When this happens under the control of Java, there are further limitations as to what can be exchanged between the environments. This is discussed under the individual methods that are affected in the JSObject description.

This table summarises the relationships at the method return interface. JavaScript values may need to be converted further if they are assigned to JavaScript LValues.

JavaScript objects are wrapped so that Java can access them as a netscape.javascript.JSObject object. When they are passed back to JavaScript, the encapsulation is removed and the intrinsic JavaScript object is accessed directly again.


See also:Java method data conversion, java.lang.Boolean, java.lang.Character, java.lang.Class, java.lang.Double, java.lang.Float, java.lang.Integer, java.lang.Long, java.lang.String, JavaArray object, JavaObject object, JavaScript to Java values, JSObject object,, JSObject.setMember(), JSObject.setSlot(), LiveConnect, Math object, netscape.javascript.JSObject, String.fromCharCode()


Wrox Professional JavaScript - page - 533