Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Kenneth A. Kousen - Making Java Groovy - 2014.pdf
Скачиваний:
50
Добавлен:
19.03.2016
Размер:
15.36 Mб
Скачать

62

CHAPTER 3 Code-level integration

3.2.5Calling Java from Groovy

Actually, this is so easy it hardly deserves a section at all. I’ve already shown it more than once. Remember the earlier example using the Google V2 geocoder (reproduced here for convenience)?

def address = [street,city,state].collect {

Java SE library code

 

 

 

 

 

 

URLEncoder.encode(it,'UTF-8')

 

 

 

 

 

}.join(',')

def params = [q:address,sensor:false,output:'csv',key:'ABQIAAAAaUT…'] def base = 'http://maps.google.com/maps/geo?'

def url = base + params.collect { k,v -> "$k=$v" }.join('&') (code,level,lat,lng) = url.toURL().text.split(',')

The integration is already here through the use of the library class and various Java methods. I needed to pass the address to Google in URL-encoded form. To do that I ran each element of the address (street, city, and state) through the java.net.URLEncoder, using its encode method. In other words, the Groovy script used a Java library class and called one of its methods.

Lessons learned (integration)

1Groovy scripts can be called with Java alone using the JSR 223 script engine.

2The Groovy Eval class makes calling scripts involving zero, one, two, or three arguments simple.

3The GroovyShell and Binding classes are used to programmatically set input variables, invoke a script, and retrieve its result.

4The easiest way to call Groovy from Java is to make a Groovy class, compile it, instantiate it in Java, and call the methods as usual.

The combination of Java and Groovy is also emphasized in Figure 3.3, shown with the original listing. In that figure each Java method and each Groovy method is indicated with arrows.

The fact that the script mixes both Java and Groovy is true of practically any Groovy script. Groovy rests on the foundation of the Java libraries. It enhances those libraries, as you’ll see in section 4.3 on the Groovy JDK, but there’s no need to reinvent the flat tire.8 Groovy is perfectly happy to use any Java classes you supply, and it makes many of them better.

COMPILE WITH GROOVYC Whenever you mix Java and Groovy, compile everything with groovyc. Let groovyc handle all the cross-compiler issues.

In the next chapter I’ll look at some of the ways Groovy improves Java.

8 Re-inventing the flat tire is what happens when you try to re-invent the wheel and get it wrong.

www.it-ebooks.info

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]