Wednesday, December 9, 2009

Rhino JavaScript Interoperability with Java

JavaScript is currently the only language supported by the CLI. The implementation used is Rhino. Overall I think that Rhino provides pretty good integration with Java. For example, I find that type conversions are handled well when calling methods of Java objects from JavaScript. The other day though, I found myself somewhat confused by an error that I was getting in a CLI script. It essentially came down to the following:

string = "abc";
string.endsWith("c");  // results an error saying, 'Cannot find function endsWith'

Initially I did not understand why I was getting the error because endsWith is in fact a method of java.lang.String. And that is when it hit me. The string variable is not a java.lang.String object. Having done a good bit of Groovy programming this was somewhat counter-intuitive to me since Groovy provides much better integration with Java by using and extending Java's type system. That same code in Groovy would compile and execute without error.

As it turned out, I did in fact want to utilize some of the methods in Java's String class in my CLI script; so, I did the following:

string = java.lang.String("abc");
string.endsWith("c");              // returns true

Here I create a Java String object which gives me full access to the Java String API. What I found really interesting is that while the conversion of my string did not work going from JavaScript to Java, it did work going from Java to JavaScript as illustrated in the next example.

string = "abc";
javaString = java.lang.String("abc");
javaString.endsWith("c");              // returns true
string == javaString;                  // returns true
javaString.slice(0, 1);                // returns 'a'

Even though string and javaString are of different types, the equality comparison yields true. Note the call to the slice() method on the last line. This is not a method of the Java String class. It is a method of the JavaScript String object, but it still evaluates without error.

The integration between Rhino and Java has its shortcomings, but overall, it is pretty good. Groovy on the other hand was designed from the ground up to be interoperable with Java and for that reason among others, it would be nice to see the CLI support Groovy.

No comments:

Post a Comment

Followers