groovy tutorial

29
vogella.de Home Blog Twitter Java Eclipse Web Technology Algorithms Source Code Browse Revision Java, Eclipse and Web programming Tutorials Groovy with Eclipse - Tutorial Lars Vogel Version 1.1 Copyright © 2008 - 2010 Lars Vogel 02.02.2010 Revision History Revision 0.1 12.11.2008 Lars Vogel Started writing this article

Upload: fj-rock

Post on 26-Nov-2014

292 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: Groovy Tutorial

vogella.de Home Blog Twitter Java Eclipse Web Technology Algorithms Source Code Browse Revision

Java, Eclipse and Web programming Tutorials

Groovy with Eclipse - Tutorial

Lars Vogel

Version 1.1

Copyright © 2008 - 2010 Lars Vogel

02.02.2010

Revision History

Revision 0.1 12.11.2008 Lars Vogel

Started writing this article

Revision 0.2 02.12.2008 Lars Vogel

First published version

Revision 0.3 10.12.2008 Lars Vogel

Page 2: Groovy Tutorial

Described the Groovy datatypes

Revision 0.4 13.12.2008 Lars Vogel

Added closures

Revision 0.5 26.01.2009 Lars Vogel

Clean-up work

Revision 0.6 15.04.2009 Lars Vogel

Update to Groovy 1.6, moved command line into appendix

Revision 0.7 31.05.2009 Lars Vogel

Improved loop examples, update for Eclipse 3.5

Revision 0.8 15.06.2009 Lars Vogel

Simplified explanation

Revision 0.9 18.07.2009 Lars Vogel

New reference

Revision 1.0 30.07.2009 Lars Vogel

Update to Eclipse 3.5 and new plugin

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.5 (Galileo) 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

Page 3: Groovy Tutorial

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. Example usage of Groovy

13.1. Groovy Classes and class variables 13.2. Elvis operator

14. Grails 15. Using Groovy classes in Java 16. Using Groovy via the command line

16.1. The Groovy shell 16.2. The Groovy Console 16.3. Compile Groovy Classes

17. Thank you 18. 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 coding 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

Page 4: Groovy Tutorial

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.5/ for Eclipse 3.5. Select the feature "Groovy-Eclipse".

3. First Groovy project

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

Page 5: Groovy Tutorial

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

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

Page 6: Groovy Tutorial

Create the class "GroovyTest"

Page 7: Groovy Tutorial

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 } }}

Page 8: Groovy Tutorial

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 per 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 per 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.

Page 9: Groovy Tutorial

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)

Page 10: Groovy Tutorial

}

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 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}

}

}

Page 11: Groovy Tutorial

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

Page 12: Groovy Tutorial

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].

Page 13: Groovy Tutorial

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

Page 14: Groovy Tutorial

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

Page 15: Groovy Tutorial

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.

Page 16: Groovy Tutorial

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; } }

Page 17: Groovy Tutorial

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" }

Page 18: Groovy Tutorial

} }

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. Example usage of Groovy

13.1. Groovy Classes and class variables

Page 19: Groovy Tutorial

All fields of a class are per 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); } }

13.2. Elvis operator

You can use the elvis operator to check if a value is null.

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

14. 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.

15. Using Groovy classes in Java

Page 20: Groovy Tutorial

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.

Page 21: Groovy Tutorial

16. 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

16.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.

Page 22: Groovy Tutorial

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.

16.2. The Groovy Console

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

16.3. Compile Groovy Classes

Page 23: Groovy Tutorial

You can also complile Groovy code into Java byte-code 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".

17. Thank you

Thank you for practicing with this tutorial.

Please note that I maintain this website in my private time. If you like the information I'm providing please help me by donating.

18. Questions and Discussion

For questions and discussion around this article please use the www.vogella.de Google Group . Also if you note an error in this article please post the error and if possible the correction to the Group.

Tip

The following tries to help you in asking good questions: 10 golden rules of asking questions in the OpenSource community .

19. Links and Literature

19.1. Groovy Links

http://groovy.codehaus.org/ Groovy Homepage

http://groovy.codehaus.org/Documentation Groovy documentation

http://grails.codehaus.org Grails Homepage

http://www.ibm.com/developerworks/java/library/j-grails01158/index.html Scott Davis introduction article to Grails

http://www.ibm.com/developerworks/java/library/j-pg04149.html Scott Davis article about loops in Groovy

http://www.ibm.com/developerworks/opensource/library/j-pg05199/index.html Scott Davis about XML processing with Groovy

_s-xclick 6292795

Page 24: Groovy Tutorial

http://www.ibm.com/developerworks/opensource/library/j-pg06239.html Scott Davis about Metaprogramming