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.

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:

  • java.io.*
  • java.lang.*
  • java.math.BigDecimal
  • java.math.BigInteger
  • java.net.*
  • java.util.*
  • groovy.lang.*
  • 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

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
')
textFile.append('By any other name would smell as sweet.
')
println textFile.text

The previous code snippet adds two lines of William Shakespeare's poem at the end of the poem.txt file, and then it prints the file contents on the console. Even though we operate solely on the java.io.File object, we call methods that did not originally exist in the JDK. Additional utility methods that appear on standard classes are described in the Groovy JDK documentation located at http://groovy.codehaus.org/groovy-jdk/. Those methods can be called due to Groovy's metaclass functionality, which is discussed in more detail in Chapter 9, Metaprogramming and DSLs in Groovy, which allows to add your own methods to any Java class used within Groovy code.

See also

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.105.2