Support free tutorials:











vogella training Training Books



Groovy with Eclipse - Tutorial

Lars Vogel

Version 1.4

08.02.2011

Revision History
Revision 0.1 12.11.2008 Lars
Vogel
Created
Revision 0.2 - 1.4 02.12.2008 - 08.02.2011 Lars
Vogel
bug fixes and enhancements

Groovy

This article gives a short overview of the Groovy language including collections, loops, gstrings, MOP, closures, operator overloading, XML handing and using Groovy together with Java class. It also describes how to use Eclipse for developing Groovy.

This article assumes that you have already Eclipse installed and that you have used Eclipse for Java development. This article was written using Groovy 1.7, Eclipse 3.6 (Helios) and Java 1.6.


Table of Contents

1. Groovy
1.1. Overview
1.2. Features
2. Installation
2.1. Groovy
2.2. Eclipse Plugin
3. First Groovy project
4. Groovy Classes, Objects and Methods
4.1. Groovy Classes
4.2. Classes and class variables
4.3. Equals, == and the method is()
4.4. Optional Parameters
5. Loops
6. Groovy Datatypes
6.1. Reference variables
6.2. Strings
6.3. Lists and maps
6.4. Ranges
7. Regular expressions
8. Closures
9. Meta Object Protocol
10. Operator overloading
11. Groovy and Files
12. Groovy and XML
13. Groovy and Concurrency
14. Example usage of Groovy
14.1. Groovy Classes and class variables
14.2. Safe Navigation Operator
14.3. Elvis operator
15. Grails
16. Using Groovy classes in Java
17. Using Groovy via the command line
17.1. The Groovy shell
17.2. The Groovy Console
17.3. Compile Groovy Classes
18. Support free vogella tutorials
18.1. Thank you
18.2. Questions and Discussion
19. Links and Literature
19.1. Groovy Links

1. Groovy

1.1. Overview

Groovy is a dynamic language which is based on the Java Virtual machine. Groovy supports standard Java constructs including annotations, generics, static imports, enums, varargs and in addition advanced language features as

Groovy is a dynamic language that runs on the JVM and is tightly integrated with the Java language. Groovy provides lots of simplifications compared to standard Java language features and advanced language features as properties, closures, native support for lists, maps and regular expressions, duck typing and the elvis operator.

Groovy is almost compatible to Java, e.g. almost every Java construct is valid Groovy code which makes the usage of Groovy for an experience Java programmer easy.

The following assumes that you have already Java programming experience and focus on Groovy specific features.

1.2. Features

While the simplicity and ease of use is the leading principle of Groovy here are a few nice features of Groovy:

  • Groovy allows to change classes and methods at runtime. For example if a class does not have a certain method and this method is called by another class the called class can decided what to do with this call.

  • Groovy does not require semicolons to separate commands if they are in different lines (separated by new-lines).

  • Groovy has list processing and regular expressions directly build into the language.

  • Groovy implements also the Builder Pattern which allows to create easily GUI's, XML Documents or Ant Tasks.

  • Asserts in Groovy will always be executed.

2. Installation

2.1. Groovy

Download the latest version from Groovy from Groovy Homepage.

You have then to set the GROOVY_HOME environment variable and add%GROOVY_HOME%/bin to your path.

Tip

If you are using MS Windows you can use the windows installer. This will set the environment variables automatically.

2.2. Eclipse Plugin

Use the Eclipse Update manager to install the Groovy Eclipse plugin. The URL for the update manager is: http://dist.springsource.org/release/GRECLIPSE/e3.6/ for Eclipse 3.6. Select the feature "Groovy-Eclipse".

3. First Groovy project

Create a new Groovy project "de.vogella.groovy.project" via File -> New -> Other -> Groovy

Create a new package "de.vogella.groovy.project".

Select File -> New -> Other -> Groovy -> Groovy Class

Create the class "GroovyTest"

Create the following code.

package de.vogella.groovy.first

class GroovyTest{
  
  static void main(def args){
    def mylist=[1,2,"Lars","4"]
    mylist.each{ println it }
  }
} 

Select the class, right-click and select "Run As" -> "Groovy Script"

This should run your Groovy class and give you output on the shell.

Congratulation! You created and run your first Groovy class.

4. Groovy Classes, Objects and Methods

4.1. Groovy Classes

A Groovy source files ends with the extension .groovy. All Groovy classes are by default public.

Create and run the following groovy class "SumItUp.groovy".

package de.vogella.groovy.first

class SumItUp {

static sum(a,b){
  a+b;
  }

static void main(args){
  println sum(1,5)
  println sum(1,2)
  }
} 

4.2. Classes and class variables

In Groovy all fields of a class have by default the access modifier "private" and Groovy provides automatically getter and setter methods for the fields. Therefore all Groovy classes are per default JavaBeans (Plain Old Java Objects).

You can use the getter and setter directly or use the name of the variable for access. Groovy will convert this to the getter and setter method.

Groovy will also directly create constructors in which you can specify the element you would like to set during construction. Groovy archives this by using the default constructor and then calling the setter methods for the attributes.

Tip

This "constructor with named paramters" works also if you call a Java class from Groovy as Groovy will again use the default constructor and then the methods to set the properties.

Have a look at the following example to see this in action.

package de.vogella.groovy.first

public class Person{
  String firstName
  String lastName
  int age
  def address
  
  static void main(def args) {
    Person p = new Person()
    // use the generated access methods
    p.setFirstName("Lars")
    // This will still use the generated access method, it is not a direct access!
    p.lastName = "Vogel" 
    p.address = ("Homestreet 3");
    println(p.firstName + " " + p.lastName);
    // use the generated constructor
    p = new Person(firstName: "Peter", lastName:"Mueller");
    println(p.firstName + " " + p.lastName);
  }
  
} 

4.3. Equals, == and the method is()

One difference between Java and Groovy is that the == operator will check for equality and not for identity. Java checks if both variables points to the same object while Groovy checks if both variables are equals. To check for identify you can use in Groovy the is() method.

Tip

Remember == in Groovy check if the objects are equals! This is different in Java.

4.4. Optional Parameters

Groovy allows to have optional parameter values. Optional parameter values are indicated by =0.

class Hello {

static main(args){
  println sum(1,5)
  println sum(1,2,5)
  }

static sum(a,b,c=0){
  a+b+c;
  }
} 

5. Loops

Create a new project "de.vogella.groovy.loops" with the package "de.vogella.groovy.loops" for this example.

Tip

The following examples use closures, which in short are "code objects". More on closures under closures Closures in Groovy.

Groovy supports the standard Java loops but also the each() method on several objects. In this method you can directly write code which should get executed. You can either directly define the name of the variable which the value of each iteration should get assigned to or using the implicit available variable "it".


package de.vogella.groovy.loops

public class PrintLoop{
  public static void main(def args){
    def list = ["Lars", "Ben", "Jack"]
    // using a variable assignment
    list.each{firstName->
      println firstName
    }
    // using the it variable
    list.each{println it}
  }
}
 

In additional your have the methods upto(), downto(), times() on number variables. Also you can use ranges (this is an additional datatype) to execute certain things from a number to another number. Please see the following example.

package de.vogella.groovy.loops

public class LoopTest{
  public static void main(args){
      5.times {println "Times + $it "}
      1.upto(3) {println "Up + $it "}
      4.downto(1) {print "Down + $it "}
      def sum = 0
      1.upto(100) {sum += 1}
      print sum
      (1..6).each {print "Range $it"}
  }  
} 

6. Groovy Datatypes

Create a new Java project de.vogella.groovy.datatypes. Create the package "de.vogella.groovy.datatypes".

6.1. Reference variables

All variables in Groovy are reference variables (objects), Groovy does not use primitive variables. Groovy still allows to use the primitives types as a short form but always translates this into the object.

Groovy allow static and dynamic typed variables. If you want to use dynamic typed variables you can use the keyword def.

If you use numbers then Groovy will automatically assign a type to it and will also make down- and upcasting for you.

Create the class "TypesTest" to test this.

package de.vogella.groovy.datatypes

public class TypesTest{
  public static void main(args){
    int i = 1 // Short form for Integer i = new Integer(1)
    int j = i +3 
    int k = i.plus(3); // Same as above
    // Make sure this worked
    assert(k==4);
    println i.getClass().getName()
    println j.getClass().getName()
    println k.getClass().getName()
    
    // Automatic type assignement
    def value = 1.0F
    println value.getClass().getName()
    def value2 = 1;
    println value2.getClass().getName()
    value2 = value2 / 2;
    println value2
    println value2.getClass().getName()
  }  
  
} 

6.2. Strings

Groovy allows to define Strings in '' and in "". Strings which are quoted in by "" are so-called GStrings (short for Groovy Strings). In GStrings you can directly use variables which will then be evaluated and included in the text.

package de.vogella.groovy.datatypes

public class StringTesting{
  
  public static void main(String[] args) {
    def name = "John"
    def s1 = "Hello $name" // $name will be replaced
    def s2 = 'Hello $name' // $name will not be replaced
    println s1
    println s2
    println s1.getClass().getName();
    println s2.getClass().getName();
  }
} 

6.3. Lists and maps

Groovy treads lists and maps as first class constructs in the language. You define a list via List list = new List[]. You can also use generics. To access element i in a list you can either use list.get(i) or list[i].

package de.vogella.groovy.datatypes

public class Person{
  String firstName;
  String lastName;
  Person(String firstName, String lastName){
    this.firstName = firstName
    this.lastName= lastName
  }
} 

package de.vogella.groovy.datatypes

public class ListMapTest{

  public static void main(args){
    List<Integer> list = [1,2,3,4]
    println list[0]
    println list[1]
    println list[2]
    List<Person> persons = list[]
    Person p = new Person("Jim", "Knopf")
    persons[0] = p
    println persons.size()
    println persons[0].firstName
    println persons.get(0).firstName
  }
} 

You can define maps via Map [key1:value1, key2:value2,...]. An empty map can be created via [:]. The values of a mapped value can get accessed via map[key]. Assignment can be done via map[key]=value.

package de.vogella.groovy.datatypes

public class MapTest{
  public static void main(args){
    Map map = [:]
    def map2 = ["Jim":"Knopf", "Thomas":"Edison"]
    println map2["Jim"]
    map2["Test"] = "Tester"
    println map2["Test"]
  }
} 

6.4. Ranges

Groovy supports ranges. Every object can be used as long as it implements previous() and next() (which are also represented by the ++ and -- operators).

package de.vogella.groovy.datatypes

public class RangesTest{
  public static void main(args){
    for (i in 0..9) {
      println ("Hello $i")
    }
  }
} 

7. Regular expressions

For an general overview of regular expression please check Regular Expressions in Java.

Groovy is based on Java regular expression support and add the following operators to make the usage of regular expressions easier:

Table 1. 

Construct Description
=~ Find: True if the pattern is contained in a text
==~ Match: True if the complete string matches the pattern
~String Turns a string into a regular expression


If you use the ~ operator such a string turns into a regular expression which can be used for pattern matching. You can use special sign (escape characters) in Strings if you put them between slashes.

package de.vogella.groovy.datatypes

public class RegularExpressionTest{
  public static void main(String[] args) {
    // Defines a string with special signs
    def text = "John Jimbo jingeled happily ever after"
    
    // Every word must be followed by a nonword character
    // Match
    if (text==~/(\w*\W+)*/){
      println "Match was successful"
    } else {
      println "Match was not successful"
    }
    // Every word must be followed by a nonword character
    // Find
    if (text=~/(\w*\W+)*/){
      println "Find was successful"
    } else {
      println "Find was not successful"
    }
    
    if (text==~/^J.*/){
      println "There was a match"
    } else {
      println "No match found"
    }
    def newText = text.replaceAll(/\w+/, "hubba")
    println newText
  }
  
  
} 

8. Closures

Closures are code fragments which can be used without being a method or a class.

A closure is defined via {para1, para2 -> code of the closure}. The values before the -> sign define the parameters of the closure. For the case that only one parameter is used you can use the implicit defined variable it.

The last statement of a closure is returned as return value.

The groovy collections have several methods which accept a closure as parameter, for example the each method.

package test

public class ClosureTest{
  public static void main(args){
    List<Integer> list = [5,6,7,8]
    list.each({line -> println line})
    list.each({println it})
  }
} 

9. Meta Object Protocol

The meta object protocol allows to add dynamically at runtime methods and properties.

If a method is called or a property is accessed in a class and this class does not define this method / property then pre-defined methods are called which can be used to handle this call.

  • def methodMissing (String name, args) - Called for missing method

  • void setProperty (String property, Object o) - called for non existing setter of a property

  • Object getProperty (String property) - called for non existing getter of a property

package de.vogella.groovy.training



public class AnyMethodExecutor{
  def map
  
  Object getProperty (String property){
    println "Setting this propery"
    return 5;
  }
  
  void setProperty (String property, Object o){
    println "Hallo"
  }
  
  def methodMissing (String name, args){
    def s = name.toUpperCase();
    if (s.startsWith("HELLO"))
    {
      println "This method stats with Hello. Full name $name" 
    } else {
      println "This method is missing"
    }
        
      
    
  }
  
  public static void main (args){
    def test = new AnyMethodExecutor ();
    test.hall();
    test.helloMethod();
    test.Hallo();
    test.test= 5;
    println test.test; 
    
  }
  
} 

10. Operator overloading

Groovy supports that you can use the standard operations in your own classes. For example if you want to use the operation a+b where a and b are from class Z then you have to implement the method plus(Z name) in class Z.

Groovy will map the operations to the following classes.

Table 2. 

Operator Name Method
a+b plus a.plus(b)
a-b minus a.minus(b)
a*b star a.multiply(b)
a/b divide a.div(b)
a%b modulo a.mod(b)
a--, --a decrement a.previous()
a++, ++a increment a.next()
a**b power a.power(b)
a-b minus a.minus(b)
a-b minus a.minus(b)


11. Groovy and Files

Processing files with groovy is simple. The following example will first print out every line to the console and then print again every line to the console with a leading line number.

package mypackage

/*
 * Writes a files to the console
 */
public class MyFile{
  public static void main(def args){
    // Write just the content of the file to the console
    File file = new File("c:/temp/groovy/content.txt")
    file.eachLine{ line -> println line }
    // adds a line number in front of each line to the console
    def lineNumber = 0;
    file = new File("c:/temp/groovy/content.txt")
    file.eachLine{ line -> 
      lineNumber++
      println "$lineNumber: $line" 
    }
  }
  
} 

12. Groovy and XML

Groovy allows to process XML very easily.

package mypackage

public class XmlTest{
  static void main(args){
    def xmldocument = '''
    <persons> 
      <person> <firstname age="3">Jim</firstname>  <lastname>Knopf </lastname> 
      </person>
      <person> <firstname age="4">Ernie</firstname>  <lastname>Bernd</lastname> 
      </person>
    </persons>
    '''
    def persons = new XmlParser().parseText(xmldocument);
    def allRecords = persons.person.size()
    println("Number of person is: $allRecords")
    def person = persons.person[0]
    // name is the name of the XML tag
    println("Name of the person tag is:" + person.name())
    // text gets the text of the node firstname
    println(person.firstname.text())
    
    // Lets print out all important information 
    for (p in persons.person){
      println "${p.firstname.text()}  ${p.lastname.text()}"
    } 
  }
  
} 

13. Groovy and Concurrency

Groovy GPars adds support for parallel processing to Groovy. It supports Actors, Map/Reduce, Dataflow, Fork/Join. You find more information on the GPars website.

14. Example usage of Groovy

14.1. Groovy Classes and class variables

All fields of a class are by default created private with automatic getter and setter. You can use the getter and setter directly or use the name of the variable for access. Groovy will convert this to the getter and setter method.

Groovy will also directly create constructors in which you can specify the element you would like to set during construction.

package de.vogella.groovy.first

public class Person{
  String firstName
  String lastName
  int age
  def address
  
  static void main(def args) {
    Person p = new Person()
    // use the generated access methods
    p.setFirstName("Lars")
    // This will still use the generated access method, it is not a direct access!
    p.lastName = "Vogel" 
    p.address = ("Homestreet 3");
    println(p.firstName + " " + p.lastName);
    // use the generated constructor
    p = new Person(firstName: "Peter", lastName:"Mueller");
    println(p.firstName + " " + p.lastName);
  }
  
} 

14.2. Safe Navigation Operator

You can use safe navigation operator to check safety for null. This will avoid a NullPointerException if you access properties of a variable which is actuall null.

// firstName will be null if user is null
// no NPE
def firstName = user?.firstName 

14.3. Elvis operator

The "Elvis operator" is a short form for the Java ternary operator. For example you can use this to set a default if an expression resolves to false or null.

// if user exists, return it, otherwise create a new User
user ?: new User() 

15. Grails

Grails is a webframework based on Groovy which allows you to develop a webapplicaiton based on convensions rather then configuration. This idea is similar to the Ruby on Rails idea. See Grails Tutorial for details.

16. Using Groovy classes in Java

To use Groovy classes in Java classes you need to add the Groovy runtime to the Java classpath.

Create a new Java project "de.vogella.groovy.java". Create package "de.vogella.groovy.java"

Create the following Groovy class.

package de.vogella.groovy.java


public class Person{
  String firstName
  String lastName
  int age
  def address
} 

Create the following Java class.

package de.vogella.groovy.java;

public class Main {
  public static void main(String[] args) {
    Person p = new Person();
    p.setFirstName("Lars");
    p.setLastName("Vogel");
    System.out.println(p.getFirstName() + " " + p.getLastName());
  }
} 

You should be able to run this Java program.

Right-click your project, select "Properties" and check that the build path includes the Groovy libraries.

17. Using Groovy via the command line

You can run Groovy code via:

  • the Groovy shell: groovysh

  • the Groovy interpreter: groovy

  • the Groovy Console : groovyConsole

  • complile Groovy code to classfiles and run it via the Java Virtual machine

17.1. The Groovy shell

The Groovy shell is the simplest way to run Groovy program. The groovy shell allow you to type in groovy commands and let them evaluate.

Open a command shell (Start-> Run -> cmd under Windows) and start the groovy shell via "groovysh". Type in the following code:

println("Hello Groovy") 

Press enter-> the system will execute your code.

17.2. The Groovy Console

Start the interactive Groovy Shell with the command groovyConsole. This console allows you to test Groovy code.

17.3. Compile Groovy Classes

You can also complile Groovy code into Java bytecode to use it from Java. To use the byte code the Groovy runtime library must included in the Java classpath.

To create Java bytecode, run the command "groovyc Hello.groovy".

18. Support free vogella tutorials

Maintaining high quality free online tutorials is a lot of work. Please support free tutorials by donating or by reporting typos and factual errors.

18.1. Thank you

Please consider a contribution if this article helped you.

Flattr this

18.2. Questions and Discussion

If you find errors in this tutorial, please notify me (see the top of the page). Please note that due to the high volume of feedback I receive, I cannot answer questions to your implementation. Ensure you have read the vogella FAQ as I don't respond to questions already answered there.

19. Links and Literature