Vogella - De: Groovy With Eclipse - Tutorial
Vogella - De: Groovy With Eclipse - Tutorial
de
Home
Blog
Twitter
Java
Eclipse
Web
Technology
Algorithms
Source Code
Browse
Revision
Version 1.1
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
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
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
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
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".
Select File -> New -> Other -> Groovy -> Groovy Class
Create the class "GroovyTest"
Create the following code.
package de.vogella.groovy.first
class GroovyTest{
This should run your Groovy class and give you output on the shell.
A Groovy source files ends with the extension .groovy. All Groovy classes are per default
public.
package de.vogella.groovy.first
class SumItUp {
static sum(a,b){
a+b;
}
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.
Have a look at the following example to see this in action.
package de.vogella.groovy.first
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 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
list.each{firstName->
println firstName
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
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.
package de.vogella.groovy.datatypes
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
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
package de.vogella.groovy.datatypes
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
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
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
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 groovy collections have several methods which accept a closure as parameter, for
example the each method.
package test
package de.vogella.groovy.training
}
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.
Table 2.
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"
}
}
package mypackage
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
13.2. Elvis operator
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.
package de.vogella.groovy.java
package de.vogella.groovy.java;
Right-click your project, select "Properties" and check that the build path includes the
Groovy libraries.
16. Using Groovy via the command line
You can run Groovy code via:
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")
Start the interactive Groovy Shell with the command groovyConsole. This console allows
you to test Groovy code.
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.
_s-xclick 6292795
Tip
The following tries to help you in asking good questions: 10 golden rules of asking
questions in the OpenSource community .