As I read the book, I asked my own“why?” question over and over: “Why wasn’t this book around when Iwas learning Groovy?” After you’ve read this book, it’s difficult to look at programmi
Trang 2What readers are saying about Programming Groovy
More than a tutorial on the Groovy language, Programming Groovy is
an excellent resource for learning the advanced concepts of ject programming, unit testing with mocks, and DSLs This is a must-have reference for any developer interested in learning to programdynamically
metaob-Joe McTee
Developer, JEKLsoft
Venkat does a fantastic job of presenting many of the advanced tures of Groovy that make it so powerful He is able to present thoseideas in a way that developers will find very easy to internalize Thisbook will help Groovy developers take their kung fu to the next level.Great work, Venkat!
fea-Jeff Brown
Member, the Groovy and Grails development teams
At this point in my career, I am really tired of reading books thatintroduce languages This volume was a pleasant breath of fresh air,however Not only has Venkat successfully translated his engagingspeaking style into a book, he has struck a good balance betweenintroductory material and those aspects of Groovy that are new andexciting Java developers will quickly grasp the relevant conceptswithout feeling like they are being insulted Readers new to the plat-form will also be comfortable with the arc he presents
Trang 3This book is an important step forward in mastering the language.Venkat takes the reader beyond simple keystrokes and syntax intothe deep depths of “why?” Groovy brings a subtle sophistication tothe Java platform that you didn’t know was missing Once you seethose missing language features in action, you can’t imagine how youever programmed without them As I read the book, I asked my own
“why?” question over and over: “Why wasn’t this book around when Iwas learning Groovy?” After you’ve read this book, it’s difficult to look
at programming on the Java platform the same way
Scott Davis
Editor-in-Chief, aboutGroovy.com; author of Groovy Recipes
Venkat neatly dissects the Groovy language—a language that is farmore than just “Java++”—in nice, edible chunks for the Groovy pro-grammer to consume If you’re a Java programmer and you’re try-ing to figure out why everybody is getting all excited about dynamiclanguages on top of the Java Virtual Machine, look no further thanVenkat’s book
Ted Neward
Java/.NET/XML services,http://www.tedneward.com
Despite signs to the contrary, Java isn’t dead—it’s just evolving.Today’s developer needs a dynamic language like Groovy in theirtoolkit, and Venkat does a tremendous job presenting this excitingnew addition to the JVM With all of his examples, you’ll be up andrunning in no time!
Nathaniel T Schutta
Author/Speaker/Teacher
I am always on the lookout for good books on the metaprogrammingfeatures of languages, and Groovy finally has one Part 3 of Venkat’sbook is devoted entirely to Groovy’s metaprogramming features.Sweet I won’t tell you which language to use, but if you are consid-ering Groovy, read Part 3 of this book
Stuart Halloway
CEO, Relevance, Inc
www.thinkrelevance.com
Trang 4This is a very well-written guide to Groovy It’s an easy read, pletely devoid of fluff, that will get you on the path to Groovy goodnessright out of the gate.
com-David Geary
Author, Clarity Training, Inc
Venkat could make rocket science sound easy He definitely makesGroovy for Java developers sound easy
Erik Weibust
Senior Architect, Credera
Trang 5Programming Groovy Dynamic Productivity for the Java Developer
Venkat Subramaniam
The Pragmatic Bookshelf
Raleigh, North Carolina Dallas, Texas
Trang 6Many of the designations used by manufacturers and sellers to distinguish their ucts are claimed as trademarks Where those designations appear in this book, and The Pragmatic Programmers, LLC was aware of a trademark claim, the designations have been printed in initial capital letters or in all capitals The Pragmatic Starter Kit, The Pragmatic Programmer, Pragmatic Programming, Pragmatic Bookshelf and the linking g device are trademarks of The Pragmatic Programmers, LLC.
prod-Every precaution was taken in the preparation of this book However, the publisher assumes no responsibility for errors or omissions, or for damages that may result from the use of information (including program listings) contained herein.
Our Pragmatic courses, workshops, and other products can help you and your team create better software and have more fun For more information, as well as the latest Pragmatic titles, please visit us at
http://www.pragprog.com
Copyright © 2008 Venkat Subramaniam.
All rights reserved.
No part of this publication may be reproduced, stored in a retrieval system, or ted, in any form, or by any means, electronic, mechanical, photocopying, recording, or otherwise, without the prior consent of the publisher.
transmit-Printed in the United States of America.
ISBN-10: 1-934356-09-3
ISBN-13: 978-1-934356-09-8
Printed on acid-free paper with 50% recycled, 15% post-consumer content.
Trang 7— Thiruvalluvar, Poet and Philosopher, 31 B.C.
(Verse 426 from Thirukural, a collection of 1330 noble couplets)
Trang 91.1 Why Dynamic Languages? 16
1.2 What’s Groovy? 19
1.3 Why Groovy? 20
1.4 What’s in This Book? 23
1.5 Who Is This Book For? 26
1.6 Acknowledgments 26
I Beginning Groovy 29 2 Getting Started 30 2.1 Getting Groovy 30
2.2 Installing Groovy 31
2.3 Test-Drive Using groovysh 32
2.4 Using groovyConsole 33
2.5 Running Groovy on the Command Line 34
2.6 Using an IDE 35
3 Groovy for the Java Eyes 37 3.1 From Java to Groovy 37
3.2 JavaBeans 45
3.3 Optional Parameters 50
3.4 Implementing Interfaces 51
3.5 Groovy boolean Evaluation 55
3.6 Operator Overloading 56
3.7 Support of Java 5 Language Features 59
3.8 Gotchas 67
Trang 10CONTENTS 10
4.1 Typing in Java 75
4.2 Dynamic Typing 78
4.3 Dynamic Typing != Weak Typing 79
4.4 Design by Capability 80
4.5 Optional Typing 86
4.6 Types in Groovy 86
4.7 Multimethods 87
4.8 Dynamic: To Be or Not to Be? 91
5 Using Closures 92 5.1 Closures 92
5.2 Use of Closures 96
5.3 Working with Closures 98
5.4 Closure and Resource Cleanup 98
5.5 Closures and Coroutines 101
5.6 Curried Closure 102
5.7 Dynamic Closures 105
5.8 Closure Delegation 107
5.9 Using Closures 110
6 Working with Strings 111 6.1 Literals and Expressions 111
6.2 GString Lazy Evaluation Problem 114
6.3 Multiline String 118
6.4 String Convenience Methods 120
6.5 Regular Expressions 121
7 Working with Collections 124 7.1 Using List 124
7.2 Iterating Over an ArrayList 126
7.3 Finder Methods 129
7.4 Collections’ Convenience Methods 130
7.5 Using Map 133
7.6 Iterating Over Map 135
7.7 Map Convenience Methods 137
Trang 11CONTENTS 11
8.1 Object Extensions 141
8.2 Other Extensions 147
9 Working with XML 155 9.1 Parsing XML 155
9.2 Creating XML 160
10 Working with Databases 164 10.1 Connecting to a Database 165
10.2 Database Select 166
10.3 Transforming Data to XML 167
10.4 Using DataSet 168
10.5 Inserting and Updating 169
10.6 Accessing Microsoft Excel 169
11 Working with Scripts and Classes 172 11.1 The Melting Pot of Java and Groovy 172
11.2 Running Groovy 173
11.3 Using Groovy Classes from Groovy 174
11.4 Using Groovy Classes from Java 175
11.5 Using Java Classes from Groovy 176
11.6 Using Groovy Scripts from Groovy 178
11.7 Using Groovy Scripts from Java 180
11.8 Ease of Integration 182
III MOPping Groovy 183 12 Exploring Meta-Object Protocol (MOP) 184 12.1 Groovy Object 185
12.2 Querying Methods and Properties 190
12.3 Dynamically Accessing Objects 192
13 Intercepting Methods Using MOP 194 13.1 Intercepting Methods Using GroovyInterceptable 194
13.2 Intercepting Methods Using MetaClass 197
Trang 12CONTENTS 12
14.1 Injecting Methods Using Categories 203
14.2 Injecting Methods Using ExpandoMetaClass 208
14.3 Injecting Methods into Specific Instances 212
14.4 Method Synthesis Using methodMissing 214
14.5 Method Synthesis Using ExpandoMetaClass 219
14.6 Synthesizing Methods for Specific Instances 222
15 MOPping Up 224 15.1 Creating Dynamic Classes with Expando 224
15.2 Method Delegation: Putting It All Together 227
15.3 Review of MOP Techniques 231
16 Unit Testing and Mocking 234 16.1 Code in This Book and Automated Unit Tests 234
16.2 Unit Testing Java and Groovy Code 236
16.3 Testing for Exceptions 240
16.4 Mocking 241
16.5 Mocking by Overriding 244
16.6 Mocking Using Categories 248
16.7 Mocking Using ExpandoMetaClass 249
16.8 Mocking Using Expando 251
16.9 Mocking Using Map 253
16.10 Mocking Using the Groovy Mock Library 254
17 Groovy Builders 260 17.1 Building XML 260
17.2 Building Swing 264
17.3 Custom Builder Using Metaprogramming 265
17.4 Using BuilderSupport 268
17.5 Using FactoryBuilderSupport 272
18 Creating DSLs in Groovy 277 18.1 Context 277
18.2 Fluency 279
18.3 Types of DSLs 280
18.4 Designing Internal DSLs 281
18.5 Groovy and DSLs 281
18.6 Closures and DSLs 282
18.7 Method Interception and DSLs 283
18.8 The Parentheses Limitation and a Workaround 285
18.9 Categories and DSLs 286
18.10 ExpandoMetaClass and DSLs 289
Trang 13CONTENTS 13
Trang 14Back in 2003, when we started Groovy, our goal was to provide Javadevelopers with an additional language to complement Java, a newSwiss Army knife to add to their tool belt Java is a great language and
a wonderful platform, but sometimes you need the agility and siveness of scripting languages or, even better, dynamic languages Wedidn’t want a new language that would be a paradigm shift for Javadevelopers Instead, Groovy was made to seamlessly integrate with Java
expres-in all possible ways while at the same time addexpres-ing all the goodiesyou would expect from a dynamic language The best of both worlds!You don’t even have to wait for Java 7, 8, or 9 to get all the nuggetsyou’d want to have in your next programming language of choice: clo-sures, properties, native syntax for lists, maps, and regular expres-sions Everything is already there
Over the course of time, Groovy has matured a lot and has become avery successful open source dynamic language used by tons of Javadevelopers and by big companies that embed it in their applicationsservers or their mission-critical applications Groovy lets you write moreexpressive unit tests and simplifies XML parsing or SQL data imports,and for your mundane tasks, there’s a scripting solution perfectly inte-grated with your Java ecosystem When you need to extend your appli-cation to customize it to your needs, you can also integrate Groovy
at specific points by injecting Groovy scripts Thanks to Groovy’s leable syntax, you can even create domain-specific languages fairly eas-ily to represent business rules that even end users can author
mal-Now, step back a little At first sight, despite the marketing taint ofthe previous paragraphs, it sounds great, and you probably see a fewplaces where you’d definitely need to use such a versatile tool But it’sjust something else you have to learn to be able to leverage it to itsfullest extent, right? You’re a Java developer, so do you fear it’s going
to be difficult to get the best out of it without wasting too much of yourtime and energy?
Trang 15FOREWORD 15
Fortunately, this book is right for you Venkat will guide you through
Groovy and its marvels Without being a boring encyclopedia, this book
covers a lot of ground And in a matter of hours (well, in fact, just the
time to read the book), you’ll be up to speed, and you’ll see how Groovy
was made by Java developers for Java developers You won’t regret your
journey, and you’ll be able to keep this book on your desk for reference
or for finding new creative ways to solve the problem of the day
Guillaume Laforge (Groovy project manager)
February 5, 2008
Trang 16Chapter 1
Introduction
As a busy Java developer, you’re constantly looking for ways to be moreproductive, right? You’re probably willing to take all the help you canget from the platform and tools available to you When I wax poeticabout the “strength of Java,” I’m not talking about the language or itssyntax It’s the Java platform that has become more capable and moreperformant To reap the benefit of the platform and to tackle the inher-ent complexities of your applications, you need another tool—one with adynamic and metaprogramming capabilities Java—the language—hasbeen flirting with that idea for a while and will support these features
to various degrees in future versions However, you don’t have to waitfor that day You can build performant Java applications with all thedynamic capabilities today, right now, using Groovy
Dynamic languages have the ability to extend a program at runtime,including changing the structure of objects, types, and behavior Dy-namic languages allow you to do things at runtime that static languages
do at compile time; they allow you to execute program statements thatwere created on the fly at runtime
For example, if you want to get the date five days from now, you canwrite this:
5.days.from.now
Yes, that’s your friendly java.lang.Integer chirping dynamic behavior inGroovy, as you’ll learn later in this book
Trang 17WHYDYNAMICLANGUAGES? 17
The flexibility offered by dynamic languages gives you the advantage
of evolving your application as it executes You are probably familiar
with code generation and code generation tools I consider code
gener-ation to be soooo 20th century In fact, generated code is like an
inces-sant itch on your back; if you keep scratching it, it turns into a sore
With dynamic languages, there are better ways I prefer code
synthe-sis, which is in-memory code creation at runtime Dynamic languages
make it easy to “synthesize code.” The code is synthesized based on the
flow of logic through your application and becomes active “just in time.”
By carefully applying these capabilities of dynamic languages, you can
be more productive as an application developer This higher
productiv-ity means you can easily create higher levels of abstractions in shorter
amounts of time You can also use a smaller, yet more capable, set
of developers to create applications In addition, greater productivity
means you can create parts of your application quickly and get
feed-back from your fellow developers, testers, domain experts, and
cus-tomer representatives And all this leads to greater agility.1
Dynamic languages have been around for a long time, so you may be
asking, why is now a great time to get excited about them? I can answer
that with four reasons:2
• Machine speed
• Availability
• Awareness of unit testing
• Killer applications
Let’s discuss each of these reasons for getting excited about dynamic
languages, starting with machine speed Doing at runtime what other
languages do at compile time first raises the concern of the speed of
dynamic languages Furthermore, interpreting code at runtime rather
than simply executing compiled code adds to that concern Fortunately,
machine speed has consistently increased over the years—handhelds
have more computing and memory power today than what large
com-puters had decades ago Tasks that were quite unimaginable using a
1 Tim O’Reilly observes the following about developing web applications: “Rather than
being finished paintings, they are sketches, continually being redrawn in response to
new data.” He also makes the point that dynamic languages are better suited for these in
“Why Scripting Languages Matter” (see Appendix A , on page 291 ).
2 A fifth reason is the ability to run dynamic languages on the JVM, but that came
much later.