Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Andrey Adamovich - Groovy 2 Cookbook - 2013.pdf
Скачиваний:
44
Добавлен:
19.03.2016
Размер:
26.28 Mб
Скачать

2

Using Groovy

Ecosystem

In this chapter, we will cover:

ff

ff

ff

ff

ff

ff

ff

ff

ff

Using Java classes from Groovy Embedding Groovy into Java Compiling Groovy code

Simplifying dependency management with Grape Integrating Groovy into the build process using Ant Integrating Groovy into the build process using Maven Integrating Groovy into the build process using Gradle Generating documentation for Groovy code

Checking Groovy code's quality with CodeNarc

Introduction

In this chapter, we will introduce the Groovy ecosystem: compilation, embedding, building, documentation, and analysis options that various, tools surrounding, Groovy offer to make your life smoother.

In the first three recipes, we will demonstrate how simple Java and Groovy interoperability is and what makes Groovy the perfect tool in a Java developer's hands. The following recipes will describe external dependency management possibilities and the most popular build tools (for example, Ant, Maven, and Gradle) integration options. Then there will be a recipe devoted to Groovydoc, which can be used to generate documentation for your sources. Finally, the last recipe will introduce a way to verify your Groovy code quality.

www.it-ebooks.info

Using Groovy Ecosystem

Using Java classes from Groovy

The Groovy language is designed in a way that it fully supports the Java syntax (there are only few minor exceptions; for example, do..while is not supported in Groovy). Most of the code that you can write in Java can automatically be considered Groovy code as well.

In this recipe, we will learn how simple it is to use existing Java classes and libraries from your Groovy code and we will explore some basic language features that makes Groovy—groovy!

How to do it...

This recipe has a rather simple setup. You can either start up the groovyConsole, as described in the Starting groovyConsole to execute Groovy snippets recipe in Chapter 1,

Getting Started with Groovy, or you can create a new file with the *.groovy extension.

1.In the groovyConsole type the following code:

import java.io.File;

File currentDir = new File("."); System.out.println("Current directory: " +

currentDir.getAbsolutePath()); File[] files = currentDir.listFiles();

for (File file: files) { System.out.println(file.getName());

}

2.Run the script to see the list of files found in the folder from where the groovyConsole was launched.

How it works...

The Groovy script from the previous section first prints the absolute path of the current directory and then the names of all the files contained in it by using the java.io.File API.

Since Groovy supports the Java syntax, you can import any class from the Java JDK in the same way you would do it in Java code.

As you can see, the code after the import statement can perfectly serve as a body of some Java method, but it is still Groovy code. On the other hand, we are still using the Java API directly.

There are several ways in which we can improve the previous script by using idiomatic Groovy syntax and without removing the java.io.File dependency.

48

www.it-ebooks.info

Chapter 2

First of all, Groovy automatically imports many classes from the Java JDK and the Groovy GDK into the scope of the script or class. The following packages do not need to be explicitly imported in Groovy, and you simply can refer to their classes:

ff java.io.* ff java.lang.*

ff java.math.BigDecimal ff java.math.BigInteger ff java.net.*

ff java.util.* ff groovy.lang.* ff groovy.util.*

For this reason, we can omit the import statements from the example script. We still need to import a class which is not located in one of the packages previously listed.

As we discussed in Chapter 1, Getting Started with Groovy, the Script class, an instance of which is created for each Groovy script, exposes the println method; this is why all calls to

System.out.println can be shortened to just println.

Another Groovy feature that can be applied to any imported class is the short notation for calling setters and getters. It allows you to write file.name instead of file.getName and

file.name = "poem.txt" instead of file.setName('poem.txt'). This feature greatly simplifies working with Java Beans and makes code much more readable (see also the Writing less verbose Java Beans with Groovy Beans recipe in Chapter 3, Using Groovy Language Features).

Famously, Groovy doesn't require a semicolon (;) at the end of a statement, if the statement is the only one in the line. We can happily omit semicolons from our script.

One more facet we can resort to in order to groovify our script is interpolation. Groovy simplifies string concatenation with the help of the ${ } operator, that is replaced with the value of the expression that appears inside it. If the expression is a simple reference to a variable or a dot expression (like in our case), then we can omit the curly brackets ({ }) and just write $currentDir.absolutePath. Or, for example, we can do the following:

def name = 'John'

println "My name is $name"

The previous code obviously yields the following:

My name is John

49

www.it-ebooks.info

Using Groovy Ecosystem

It is worth knowing that strings containing expression are actually GString in Groovy and not normal java.lang.String. String interpolation is only done for strings enclosed in double quotes ("). If you want to avoid string interpolation, then you can use single quotes (') or escape the dollar sign; that is, \$:

def price = 8

println "Item price: \$${price}"

The previous code snippet will print:

Item price: $8

Thanks to the dynamic nature of the language, we can also omit specifying the variable type in the variable declaration. We can just use the def keyword instead.

Taking all the previous notes into account, the code can be shortened to:

def currentDir = new File('.')

println "Current directory ${currentDir.absolutePath}" def files = currentDir.listFiles()

for (def file: files) { println file.name

}

There are a few other features of Groovy that can help to make this script even more concise such as closures and metaclass facilities, but those will be discussed in more detail in

Chapter 3, Using Groovy Language Features.

Under the hood (either for dynamic scripts or Groovy classes compiled through groovyc), Groovy code is always compiled into Java bytecode. Every direct call to an imported Java class would act in the exact same way as it would if it were a Java code.

There's more...

For many standard JDK classes, Groovy provides API extensions. For example, instances of the java.io.File class have methods such as append or getText:

def textFile = new File('poem.txt') textFile.append('What\'s in a name? ') textFile.append('That which we call a rose\n') textFile.append('By any other name would smell as sweet.\n') println textFile.text

50

www.it-ebooks.info

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