Java Reference
In-Depth Information
3.1. Integrating Java with other languages
Combining Java with other languages has always been a challenge. Java historically hasn't
played well with others. [ 1 ] The only API designed from the beginning for Java to call func-
tions written in other languages is JNI, the Java Native Interface, which is awkward to use
even in the best of circumstances. [ 2 ] The past few years, however, have seen the rise of
entire families of languages that compile directly to bytecodes that run on the JVM, from
Groovy to Scala to Clojure, as well as bridge languages like Jython or JRuby that allow
you to run code written in Python or Ruby on the JVM. From the point of view of these
“alternative” JVM-based languages, Java's real contribution isn't the language itself, but
rather the virtual machine and the associated Java libraries. JVM-based languages take ad-
vantage of the Java infrastructure and try to handle any Java-specific drawbacks.
1 Of course, this is true of most languages.
2 Once, back in the late 1990s, I had to build a Java Swing user interface in front of an engineering system written
in Fortran. I used JNI to go from Java to C and then from C to Fortran. The results were like putting a notch into a
wooden beam and saying, “I want you to break right here.”
JVM
Ultimately, Java's biggest contribution isn't the language; it's the virtual machine.
Whenever a new capability is integrated into Java's basic infrastructure, a Java Specific-
ation Request (JSR) is created to provide a standard implementation mechanism. In the
integration case, the JSR in question is JSR 223, Scripting for the Java Platform ( ht-
tp://jcp.org/en/jsr/detail?id=223 ) . The purpose of the JSR is to allow other (presumably
scripting) languages to be invoked from Java. Although most of this topic will assume that
you're mixing Java and Groovy on a class-by-class basis, for the sake of completeness I'll
review here how to call a Groovy script from Java, both using the JSR technique and using
library classes provided by Groovy for that purpose.
Groovy is much closer to Java than the script integration story suggests, however. As I'll
demonstrate in the section on calling Java from Groovy rather than the other way around,
virtually every Groovy program of any size uses Java already. Groovy code can instantiate
a Java class, call a method Groovy added to it (the so-called Groovy JDK highlighted in
chapter 4 , section 4.3 ) , and call additional Java methods on the result. The question then
 
 
Search WWH ::




Custom Search