Programming Groovy.Pdf
Total Page:16
File Type:pdf, Size:1020Kb
What 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 metaob- ject programming, unit testing with mocks, and DSLs. This is a must- have reference for any developer interested in learning to program dynamically. Joe McTee Developer, JEKLsoft Venkat does a fantastic job of presenting many of the advanced fea- tures of Groovy that make it so powerful. He is able to present those ideas in a way that developers will find very easy to internalize. This book will help Groovy developers take their kung fu to the next level. Great work, Venkat! Jeff Brown Member, the Groovy and Grails development teams At this point in my career, I am really tired of reading books that introduce languages. This volume was a pleasant breath of fresh air, however. Not only has Venkat successfully translated his engaging speaking style into a book, he has struck a good balance between introductory material and those aspects of Groovy that are new and exciting. Java developers will quickly grasp the relevant concepts without feeling like they are being insulted. Readers new to the plat- form will also be comfortable with the arc he presents. Brian Sletten Zepheira, LLC You simply won’t find a more comprehensive resource for getting up to speed on Groovy metaprogramming. Jason Rudolph Author, Getting Started with Grails This book is an important step forward in mastering the language. Venkat takes the reader beyond simple keystrokes and syntax into the deep depths of “why?” Groovy brings a subtle sophistication to the Java platform that you didn’t know was missing. Once you see those missing language features in action, you can’t imagine how you ever programmed without them. As I read the book, I asked my own “why?” question over and over: “Why wasn’t this book around when I was 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 far more 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 dynamic languages on top of the Java Virtual Machine, look no further than Venkat’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 their toolkit, and Venkat does a tremendous job presenting this exciting new addition to the JVM. With all of his examples, you’ll be up and running in no time! Nathaniel T. Schutta Author/Speaker/Teacher I am always on the lookout for good books on the metaprogramming features of languages, and Groovy finally has one. Part 3 of Venkat’s book 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 This is a very well-written guide to Groovy. It’s an easy read, com- pletely devoid of fluff, that will get you on the path to Groovy goodness right out of the gate. David Geary Author, Clarity Training, Inc. Venkat could make rocket science sound easy. He definitely makes Groovy for Java developers sound easy. Erik Weibust Senior Architect, Credera Programming Groovy Dynamic Productivity for the Java Developer Venkat Subramaniam The Pragmatic Bookshelf Raleigh, North Carolina Dallas, Texas Many of the designations used by manufacturers and sellers to distinguish their prod- 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. 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 transmit- ted, in any form, or by any means, electronic, mechanical, photocopying, recording, or otherwise, without the prior consent of the publisher. 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. – “As moves the world, to move in tune with changing times and ways is wisdom” — Thiruvalluvar, Poet and Philosopher, 31 B.C. (Verse 426 from Thirukural, a collection of 1330 noble couplets) Contents Foreword 14 1 Introduction 16 1.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 CONTENTS 10 4 Dynamic Typing 75 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 UsingList ........................... 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 CONTENTS 11 II Using Groovy 140 8 Exploring the GDK 141 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 CONTENTS 12 14 MOP Method Injection and Synthesis 202 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