+

Search Tips   |   Advanced Search

Ambiguous Function Calls

Java also provides a primitive type called a char, which can contain a single character value. A collection of characters could be represented in Java as an array of character primitives, or it could be handled as a java.lang.String object. As mentioned before, JavaScript does not savvy primitives. Character data must be dealt with using the JavaScript string object. Even if you specify a single character in JavaScript ("a"), this is considered a string.

Now consider that when you call a Java function from your script, this is matched up to the actual method using the name of the function as well as the number and types of the parameters used in the call. This matching is carried out by the LiveConnect extension to JavaScript. LiveConnect does its best to figure out which function signature you are referring to, which is no small task given that Java and JavaScript represent parameter types in different ways. But JavaScript and LiveConnect do some internal conversions for you, trying to match up Java and JavaScript data types.

A problem arises when you have multiple versions of a single method, each taking a different set of parameters; in particular, if two functions have the same number of parameters, but of different types, and if these types are not differentiated in JavaScript. Let's take a look at an example script that will be performing an MD5 encryption of a string.

// Create MessageDigest object for MD5 hash
var md = new java.security.MessageDigest.getInstance( "MD5" );

// Get the EID attribute value as byte array.
var ab = java.lang.String( "message to encrypt" ).getBytes();

md.update( ab );

var retHash = md.digest();
The above update() call will fail with an evaluation exception stating that the function call is ambiguous. This is because the MessageDigest object has multiple versions of this function with similar signatures: one accepting a single byte and one expecting a byte array (byte[]). We can get around this if we can find another variant of the same method taking a different number of parameters, thus giving it a uniquely identifiable signature. Fortunately, MessageDigest provides something suitable: a version of update() that takes a byte array plus a couple of numeric values (offset and length parameters). So we can change your code to use this call instead:
md.update( ab, 0, ab.length );
Finally, we can always specify the exact signature of the Java method you want to use by quoting it inside brackets after the object:
md["update(byte[])"](ab);
Here we are calling for the version of the update() function declared with a single byte array parameter.


Parent topic:

Java + Script ≠ JavaScript