100% found this document useful (1 vote)
7 views

Programming Groovy Dynamic Productivity for the Java Developer 1st Edition Venkat Subramaniam download

The document provides links to various programming ebooks by Venkat Subramaniam, including titles on Groovy, Scala, and concurrency on the JVM. It features reader testimonials highlighting the effectiveness of Subramaniam's teaching style and the depth of content in his books. The document also includes a brief overview of the contents and structure of 'Programming Groovy: Dynamic Productivity for the Java Developer'.

Uploaded by

sumiacheap05
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
7 views

Programming Groovy Dynamic Productivity for the Java Developer 1st Edition Venkat Subramaniam download

The document provides links to various programming ebooks by Venkat Subramaniam, including titles on Groovy, Scala, and concurrency on the JVM. It features reader testimonials highlighting the effectiveness of Subramaniam's teaching style and the depth of content in his books. The document also includes a brief overview of the contents and structure of 'Programming Groovy: Dynamic Productivity for the Java Developer'.

Uploaded by

sumiacheap05
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 62

Programming Groovy Dynamic Productivity for the

Java Developer 1st Edition Venkat Subramaniam


download

https://ebookname.com/product/programming-groovy-dynamic-
productivity-for-the-java-developer-1st-edition-venkat-
subramaniam/

Get Instant Ebook Downloads – Browse at https://ebookname.com


Instant digital products (PDF, ePub, MOBI) available
Download now and explore formats that suit you...

Programming Groovy 2 Dynamic Productivity for the Java


Developer 2nd Edition Venkat Subramaniam

https://ebookname.com/product/programming-groovy-2-dynamic-
productivity-for-the-java-developer-2nd-edition-venkat-
subramaniam/

Programming Scala Tackle Multi Core Complexity on the


Java Virtual Machine 1st Edition Venkat Subramaniam

https://ebookname.com/product/programming-scala-tackle-multi-
core-complexity-on-the-java-virtual-machine-1st-edition-venkat-
subramaniam/

Programming Concurrency on the JVM Mastering


Synchronization STM and Actors Venkat Subramaniam

https://ebookname.com/product/programming-concurrency-on-the-jvm-
mastering-synchronization-stm-and-actors-venkat-subramaniam/

Sociological Theory in the Classical Era Text and


Readings 3rd Edition Edition Laura Desfor And Scott
Appelrouth

https://ebookname.com/product/sociological-theory-in-the-
classical-era-text-and-readings-3rd-edition-edition-laura-desfor-
and-scott-appelrouth/
Security and Trends in Wireless Identification and
Sensing Platform Tags Advancements in RFID 1st Edition
Pedro Peris Lopez

https://ebookname.com/product/security-and-trends-in-wireless-
identification-and-sensing-platform-tags-advancements-in-
rfid-1st-edition-pedro-peris-lopez/

Lake Taihu China Dynamics and Environmental Change


Monographiae Biologicae 1st Edition Boqiang Qin

https://ebookname.com/product/lake-taihu-china-dynamics-and-
environmental-change-monographiae-biologicae-1st-edition-boqiang-
qin/

The Ecological Approach to Visual Perception Classic


Edition James J. Gibson

https://ebookname.com/product/the-ecological-approach-to-visual-
perception-classic-edition-james-j-gibson/

Practicing Materiality 1st Edition Ruth M. Van Dyke

https://ebookname.com/product/practicing-materiality-1st-edition-
ruth-m-van-dyke/

Historical Dictionary Of The Cold War 2nd Edition


Edition Joseph Smith

https://ebookname.com/product/historical-dictionary-of-the-cold-
war-2nd-edition-edition-joseph-smith/
Primitive Mental States A Psychoanalytic Exploration of
the Origins of Meaning 1st Edition Jane Van Buren (Ed.)

https://ebookname.com/product/primitive-mental-states-a-
psychoanalytic-exploration-of-the-origins-of-meaning-1st-edition-
jane-van-buren-ed/
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 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
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 . . . . . . . . . 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
CONTENTS 13

A Web Resources 291

B Bibliography 296

Index 298
Foreword
Back in 2003, when we started Groovy, our goal was to provide Java
developers with an additional language to complement Java, a new
Swiss Army knife to add to their tool belt. Java is a great language and
a wonderful platform, but sometimes you need the agility and expres-
siveness of scripting languages or, even better, dynamic languages. We
didn’t want a new language that would be a paradigm shift for Java
developers. Instead, Groovy was made to seamlessly integrate with Java
in all possible ways while at the same time adding all the goodies
you 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 nuggets
you’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 a
very successful open source dynamic language used by tons of Java
developers and by big companies that embed it in their applications
servers or their mission-critical applications. Groovy lets you write more
expressive 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 mal-
leable syntax, you can even create domain-specific languages fairly eas-
ily to represent business rules that even end users can author.
Now, step back a little. At first sight, despite the marketing taint of
the previous paragraphs, it sounds great, and you probably see a few
places where you’d definitely need to use such a versatile tool. But it’s
just something else you have to learn to be able to leverage it to its
fullest 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 your
time and energy?
F OREWORD 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
Chapter 1

Introduction
As a busy Java developer, you’re constantly looking for ways to be more
productive, right? You’re probably willing to take all the help you can
get from the platform and tools available to you. When I wax poetic
about the “strength of Java,” I’m not talking about the language or its
syntax. It’s the Java platform that has become more capable and more
performant. To reap the benefit of the platform and to tackle the inher-
ent complexities of your applications, you need another tool—one with a
dynamic and metaprogramming capabilities. Java—the language—has
been flirting with that idea for a while and will support these features
to various degrees in future versions. However, you don’t have to wait
for that day. You can build performant Java applications with all the
dynamic capabilities today, right now, using Groovy.

1.1 Why Dynamic Languages?


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 that
were created on the fly at runtime.
For example, if you want to get the date five days from now, you can
write this:
5.days.from.now

Yes, that’s your friendly java.lang.Integer chirping dynamic behavior in


Groovy, as you’ll learn later in this book.
W HY D YNAMIC L ANGUAGES ? 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.
W HY D YNAMIC L ANGUAGES ? 18

1980s processor are easy to achieve today. The performance concerns


of dynamic languages are greatly eased because of processor speeds
and other improvements in our field, including better just-in-time com-
pilation techniques.
Now let’s talk about availability. The Internet and active “public” com-
munity-based development have made recent dynamic languages eas-
ily accessible and available. Developers can now easily download lan-
guages and tools and play with them. They can even participate in
community forums to influence the evolution of these languages.3 This
is leading to greater experimentation, learning, and adaptation of lan-
guages than in the past.
Now it’s time to talk about the awareness of unit testing. Most dynamic
languages are dynamically typed. The types are often inferred based
on the context. There are no compilers to flag type-casting violations
at compile time. Since quite a bit of code may be synthesized and your
program can be extended at runtime, you can’t simply rely upon coding-
time verification alone. Writing code in dynamic languages requires a
greater discipline from the testing point of view. Over the past few years,
we’ve seen greater awareness among programmers (though not suffi-
ciently greater adoption yet) in the area of testing in general and unit
testing in particular. Most of the programmers who have taken advan-
tage of these dynamic languages for commercial application develop-
ment have also embraced testing and unit testing.4
Finally, let’s discuss the fourth bullet point listed earlier. Many devel-
opers have in fact been using dynamic languages for decades. How-
ever, for the majority of the industry to be excited about them, we
had to have killer applications—those compelling stories to share with
your developers and managers. That tipping point, for Ruby in partic-
ular and for dynamic languages in general, came in the form of Rails
([TH05], [SH07], [Tat06]). Rails showed struggling web developers how
they could quickly develop applications using the dynamic capabilities
of Ruby. Along the same vein came Grails built using Groovy and Java,
Django built using Python, and Lift built using Scala, to mention a few.

3. The Groovy users mailing list is very active, with constant discussions from passion-
ate users expressing opinions, ideas, and criticisms on current and future features. Visit
http://groovy.codehaus.org/Mailing+Lists and http://groovy.markmail.org if you don’t believe me.
4. “Legacy code is simply code without tests.” —Michael C. Feathers [Fea04]
W HAT ’ S G ROOVY ? 19

These frameworks have caused enough stir in the development commu-


nity to make the industry-wide adoption of dynamic languages a highly
probable event in the near future.
I find that dynamic languages, along with metaprogramming capabil-
ities, make simple things simpler and harder things manageable. You
still have to deal with the inherent complexity of your application, but
dynamic languages let you focus your effort where it’s deserved. When I
got into Java (after years of C++), features such as reflection, a good set
of libraries, and evolving framework support made me productive. The
JVM, to a certain extent, provided me with the ability to take advan-
tage of metaprogramming. However, I had to use something in addition
to Java to tap into that potential—heavyweight tools such as AspectJ.
Like several other productive programmers, I found myself left with two
options. The first option was to use the exceedingly complex and not-
so-flexible Java along with heavyweight tools. The second option was
to move on to using dynamic languages such as Ruby that are object-
oriented and have metaprogramming capability built in (for instance, it
takes only a couple of lines of code to do AOP in Ruby and Groovy). A
few years ago, taking advantage of dynamic capabilities and metapro-
gramming and being productive at the same time meant leaving behind
the Java platform. (After all, you use these features to be productive
and can’t let them slow you down, right?) That is not the case any-
more. Languages such as Groovy and JRuby are dynamic and run on
the JVM. They allow you to take full advantage of both the rich Java
platform and dynamic language capabilities.

1.2 What’s Groovy?


Groovy5 is a lightweight, low-ceremony, dynamic, object-oriented lan-
guage that runs on the JVM. Groovy is open sourced under Apache
License, version 2.0. It derives strength from different languages such
as Smalltalk, Python, and Ruby while retaining a syntax familiar to
Java programmers. Groovy compiles into Java bytecode and extends
the Java API and libraries. It runs on Java 1.4 or newer. For deploy-
ment, all you need is a Groovy JAR in addition to your regular Java
stuff, and you’re all set.

5. Merriam-Webster defines Groovy as “marvelous, wonderful, excellent, hip, trendy.”


W HY G ROOVY ? 20

I like to define Groovy as “a language that has been reborn several


times.”6 James Strachan and Bob McWhirter started it in 2003, and it
was commissioned into Java Specification Request (JSR 241) in March
2004. Soon after, it was almost abandoned because of various difficul-
ties and issues. Guillaume Laforge and Jeremy Rayner decided to rekin-
dle the efforts and bring Groovy back to life. Their first effort was to fix
bugs and stabilize the language features. The uncertainty lingered on
for a while. I know a number of people (committers and users) who sim-
ply gave up on the language at one time. Finally, a group of smart and
enthusiastic developers joined force with Guillaume and Jeremy, and a
vibrant developer community emerged. JSR version 1 was announced
in August 2005.
Groovy version 1.0 release was announced on January 2, 2007. It was
encouraging to see that, well before it reached 1.0, Groovy was put
to use on commercial projects in a handful of organizations in the
United States and Europe. In fact, I’ve seen growing interest in Groovy
in conferences and user groups around the world. Several organiza-
tions and developers are beginning to use Groovy at various levels on
their projects, and I think the time is ripe for major Groovy adoption in
the industry. Groovy version 1.5 was released on December 7, 2007.
Grails ([Roc06], [Rud07]),7 built using Groovy and Java, is a dynamic
web development framework based on “coding by convention.” It allows
you to quickly build web applications on the JVM using Groovy, Spring,
Hibernate, and other Java frameworks.

1.3 Why Groovy?


As a Java programmer, you don’t have to switch completely to a differ-
ent language. Trust me, Groovy feels like the Java language you already
know with but with a few augmentations.
There are dozens of scripting languages8 that can run on the JVM, such
as Groovy, JRuby, BeanShell, Scheme, Jaskell, Jython, JavaScript, etc.
The list could go on and on. Your language choice should depend on a
number of criteria: your needs, your preferences, your background, the
projects you work with, your corporate technical environment, and so

6. See “A bit of Groovy history,” a blog by Guillaume Laforge at http://glaforge.free.fr/


weblog/index.php?itemid=99.
7. See Jason Rudolph’s “Getting Started with Grails” in Appendix A, on page 291.
8. https://scripting.dev.java.net
W HY G ROOVY ? 21

on. In this section, I will discuss whether Groovy is the right language
for you.
As a programmer, I am shameless about languages. I can comfortably
program in about eight structured, object-oriented, and functional pro-
gramming languages and can come dangerously close to writing code
in a couple more. In any given year, I actively code in about two to three
languages at least. So, if one thing, I am pretty unbiased when it comes
to choosing a language—I will pick the one that works the best for a
given situation. I am ready to change to another language with the ease
of changing a shirt, if that is the right thing to do, that is.
Groovy is an attractive language for a number of reasons:
• It has a flat learning curve.
• It follows Java semantics.
• It bestows dynamic love.
• It extends the JDK.
I’ll now expand on these reasons. First, you can take almost any Java
code9 and run it as Groovy. The significant advantage of this is a flat
learning curve. You can start writing code in Groovy and, if you’re
stuck, simply switch gears and write the Java code you’re familiar with.
You can later refactor that code and make it groovier.
For example, Groovy understands the traditional for loop. So, you can
write this:
// Java Style
for(int i = 0; i < 10; i++)
{
//...
}

As you learn Groovy, you can change that to the following code or one
of the other flavors for looping in Groovy (don’t worry about the syntax
right now; after all, you’re just getting started, and very soon you’ll be
a pro at it):
10.times {
//...
}

9. See Section 3.8, Gotchas, on page 67 for known problem areas.


W HY G ROOVY ? 22

Second, when programming in Groovy, you can expect almost every-


thing you expect in Java. Groovy classes extend the same good old
java.lang.Object—Groovy classes are Java classes. The OO paradigm
and Java semantics are preserved, so when you write expressions and
statements in Groovy, you already know what those mean to you as a
Java programmer.
Here’s a little example to show you that Groovy classes are Java classes:
Download Introduction/UseGroovyClass.groovy

println XmlParser.class
println XmlParser.class.superclass

If you run groovy UseGroovyClass, you’ll get the following output:


class groovy.util.XmlParser
class java.lang.Object

Now let’s talk about the third reason to love Groovy. Groovy is dynamic,
and it is optionally typed. If you’ve enjoyed the benefits of other dynamic
languages such as Smalltalk, Python, JavaScript, and Ruby, you can
realize those in Groovy. If you had looked at Groovy 1.0 support for
metaprogramming, it probably left you desiring for more. Groovy has
come a long way since 1.0, and Groovy 1.5 has pretty decent metapro-
gramming capabilities.
For instance, if you want to add the method isPalindrome( ) to String—a
method that tells whether a word spells the same forward and back-
ward—you can add that easily with only a couple lines of code (again,
don’t try to figure out all the details of how this works right now; you
have the rest of the book for that):
Download Introduction/Palindrome.groovy

String.metaClass.isPalindrome = {->
delegate == delegate.reverse()
}

word = 'tattarrattat'
println "$word is a palindrome? ${word.isPalindrome()}"
word = 'Groovy'
println "$word is a palindrome? ${word.isPalindrome()}"

The following output shows how the previous code works:


tattarrattat is a palindrome? true
Groovy is a palindrome? false

Finally, as a Java programmer, you rely heavily on the JDK and the API
to get your work done. These are still available in Groovy. In addition,
W HAT ’ S IN T HIS B OOK ? 23

Groovy extends the JDK with convenience methods and closure support
through the GDK. Here’s a quick example of an extension in GDK to the
java.util.ArrayList class:
lst = ['Groovy' , 'is' , 'hip' ]
println lst.join(' ' )
println lst.getClass()

The output from the previous code confirms that you’re still working
with the JDK but that you used the Groovy-added join( ) method to con-
catenate the elements in the ArrayList:
Groovy is hip
class java.util.ArrayList

You can see how Groovy takes the Java you know and augments it.
If your project team is familiar with Java, if they’re using it for most
of your organization’s projects, and if you have a lot of Java code to
integrate and work with, then you will find that Groovy is a nice path
toward productivity gains.

1.4 What’s in This Book?


This book is about programming using the Groovy language. I make no
assumptions about your knowledge of Groovy or dynamic languages,
although I do assume you are familiar with Java and the JDK. Through-
out this book, I will walk you through the concepts of the Groovy lan-
guage, presenting you with enough details and a number of examples
to illustrate the concepts. My objective is for you to get proficient with
Groovy by the time you put this book down, after reading a substantial
portion of it, of course.
The rest of this book is organized as follows:
The book has has three parts: “Beginning Groovy,” “Using Groovy,” and
“MOPping Groovy.”
In the chapters in Part 1, “Beginning Groovy,” I focus on the whys and
whats of Groovy—those fundamentals that’ll help you get comfortable
with general programming in Groovy. Since I assume you’re familiar
with Java, I don’t spend any time with programming basics, like what
an if statement is or how to write it. Instead, I take you directly to the
similarities of Groovy and Java and topics that are specific to Groovy.
In the chapters in Part 2, “Using Groovy,” I focus on how to use Groovy
for everyday coding—working with XML, accessing databases, and
W HAT ’ S IN T HIS B OOK ? 24

working with multiple Java/Groovy classes and scripts—so you can put
Groovy to use right away for your day-to-day tasks. I also discuss the
Groovy extensions and additions to the JDK so you can take advantage
of both the power of Groovy and the JDK at the same time.
In the chapters in Part 3, “MOPping Groovy,” I focus on the metapro-
gramming capabilities of Groovy. You’ll see Groovy really shine in these
chapters and learn how to take advantage of its dynamic nature. You’ll
start with the fundamentals of MetaObject Protocol (MOP), learn how to
do aspect-oriented programming (AOP) such as operations in Groovy,
and learn about dynamic method/property discovery and dispatching.
Then you’ll apply those right away to creating and using builders and
domain-specific languages (DSLs). Unit testing is not only necessary in
Groovy because of its dynamic nature, but it is also easier to do—you
can use Groovy to unit test your Java and Groovy code, as you’ll see in
this part of the book.
Here’s what’s in each chapter:
Part 1: “Beginning Groovy”
In Chapter 2, Getting Started, on page 30, you’ll download and install
Groovy and take it for a test-drive right away using groovysh and groovy-
Console. You’ll also learn how to run Groovy without these tools—from
the command line and within your IDEs.
In Chapter 3, Groovy for the Java Eyes, on page 37, you’ll start with
familiar Java code and refactor that to Groovy. After a quick tour of
Groovy features that improve your everyday Java coding, you’ll learn
about Groovy’s support for Java 5 features. Groovy follows Java seman-
tics, except in places it does not—you’ll also learn gotchas that’ll help
avoid surprises.
In Chapter 4, Dynamic Typing, on page 75, you’ll see how Groovy’s
typing is similar and different from Java’s typing, what Groovy really
does with the type information you provide, and when to take advan-
tage of dynamic typing vs. optional typing. You’ll also learn how to take
advantage of Groovy’s dynamic typing, design by capability, and multi-
methods.
In Chapter 5, Using Closures, on page 92, you’ll learn all about the
exciting Groovy feature called closures, including what they are, how
they work, and when and how to use them.
W HAT ’ S IN T HIS B OOK ? 25

In Chapter 6, Working with Strings, on page 111, you’ll learn about


Groovy strings, working with multiline strings, and Groovy’s support
for regular expressions.
In Chapter 7, Working with Collections, on page 124, you’ll explore
Groovy’s support for Java collections—lists and maps. You’ll learn var-
ious convenience methods on collections, and after this chapter, you’ll
never again want to use your collections the old way.
Part 2: “Using Groovy”
Groovy embraces and extends the JDK. You’ll explore the GDK and
learn the extensions to Object and other Java classes in Chapter 8,
Exploring the GDK, on page 141.
Groovy has pretty good support for working with XML, including pars-
ing and creating XML documents, as you’ll see in Chapter 9, Working
with XML, on page 155.
Chapter 10, Working with Databases, on page 164 presents Groovy’s
SQL support, which will make your database-related programming easy
and fun. In this chapter, you’ll learn about iterators, datasets, and how
to perform regular database operations using simpler syntax and clo-
sures. I’ll also show how to get data from Microsoft Excel documents.
One of the key strengths of Groovy is the integration with Java. In
Chapter 11, Working with Scripts and Classes, on page 172, you’ll learn
ways to closely interact with multiple Groovy scripts, Groovy classes,
and Java classes from within your Groovy and Java code.
Part 3: “MOPping Groovy”
Metaprogramming is one of the biggest benefits of dynamic languages
and Groovy; it has the ability to inspect classes at runtime and dynam-
ically dispatch method calls. You’ll explore Groovy’s support for meta-
programming in Chapter 12, Exploring Meta-Object Protocol (MOP), on
page 184, beginning with the fundamentals of how Groovy handles
method calls to Groovy objects and Java objects.
Groovy allows you to perform AOP-like method interceptions using
GroovyInterceptable and ExpandoMetaClass, as you’ll see in Chapter 13,
Intercepting Methods Using MOP, on page 194.
In Chapter 14, MOP Method Injection and Synthesis, on page 202, you’ll
dive into Groovy metaprogramming capabilities that allow you to inject
and synthesize methods at runtime.
Another Random Document on
Scribd Without Any Related Topics
now turn to the poet's life, and examine the part played by
environment, race, and parentage in moulding his character.
Heine was born in Düsseldorf on December 1797, and not as is
currently supposed in 1799.
The Catholic Rhineland, in which Düsseldorf is situated, rebelled
more than almost any other district in Germany against the
despotism of the Prussian bureaucracy; it possessed an almost
southern joie de vivre, and only naturally exhibited a distinct
inclination to the Catholicism of the Romanticists, all of which
characteristics in a greater or less degree are to be found in Heine.
Further, Heine was a Jew, possessing, in consequence, an hereditary
tendency to gravitate to the extreme left wing both of thought and
of politics, while the inborn Judenschmerz in his heart was
aggravated by the anti-Semitic reaction which followed the
benevolent tolerance of Napoleon.
The poet's father, Samson Heine, was an easy-going, æsthetic
nonentity in moderate circumstances, who does not appear to have
exercised any serious influence on the child's development. This was
accomplished by the mother, née von Geldern, a cultured and
strong-minded woman, and a Voltairean by belief, who did her best
to foster and stimulate her son's youthful intelligence. The favourite
authors of the young Heine were Cervantes, Sterne, and Swift. Of
contemporaries, the two men who exercised any real influence were
the Emperor Napoleon, and Byron, "the kingly man" and the
aristocratic revolutionary. Napoleon in particular was the god of his
boyish adoration. This Napoleonic enthusiasm was largely fostered
by Heine's friendship with a grenadier drummer of the French army
named Le Grand, while it reached its climax when he beheld with his
own eyes the beatific vision of the Emperor himself riding on his
beautiful white palfrey through the Hofgarten Allee at Düsseldorf, in
splendid defiance of the police regulations, which forbade such
riding under a penalty of five thalers.
This worship of the Emperor, moreover, resulted in the wonderful
poem called "The Grenadiers," written at the age of eighteen. The
swing and power of the poem have made it classic, especially the
great final stanza beginning:
"Denn reitet mein Kaiser wohl über mein Grab."
Heine received his early education at a Jesuit monastery. The first
event of any moment in his life, however, is his calf-love for Josepha,
or Sefchen, the executioner's daughter, a weird fantastic beauty of
fifteen, with large dark eyes and blood-red hair. Josepha was the
inspiration of the juvenile Dream Pictures incorporated subsequently
in the Book of Songs, and exhibiting a genuine power and an even
more genuine promise.
In 1816 Heine was sent into the office of Solomon Heine, his
millionaire uncle of Hamburg.
He seems to have been singularly destitute of the financial genius of
his race, and the business career proved from the outset a fiasco.
The real key, however, to the three years spent in Hamburg is
supplied not by Money, but by Love. Having served his
apprenticeship in Düsseldorf with his calf-attachment to the
executioner's daughter, Heine proceeded straightway to a grande
passion for his uncle's pretty daughter Amalie. His love was not
reciprocated, and in 1821 the beauteous Amalie married a wealthy
landowner of Königsberg. This Amalie incident was one of the most
important in Heine's life, and is largely responsible for his early
cynicism. He was disillusioned with a vengeance, and could now with
his own eyes inspect the flimsy material of which "Love's Young
Dream" is wove. Though, however, a great personal blow, this
abortive passion is also to be regarded as an invaluable æsthetic
asset. The poet of necessity is bound to write of his own personal
impressions and experiences; and it is obvious that the intenser are
these experiences, the more vital will be his poetry. If Heine's love
for Amalie was the accursed flame that seared his soul, it was also
the sacred fire that kindled his inspiration, and it is to Amalie that we
owe not only a great part of the Book of Songs, but also much which
is characteristic of Heine's subsequent life-outlook.
In 1819, probably because Heine had given convincing proofs of his
business inefficiency, it was decided that he should go to Bonn to
study law. He neglected his studies, and it was not long before he
fell foul of the authorities, owing to his anticipation in the
proceedings of the Burschenschaften or student political unions.
In 1820 Heine left Bonn for Göttingen. At Göttingen his career was
brief but thrilling, and he was rusticated after a few months on
account of a proposed duel with an impertinent junker.
Transferring his quarters to Berlin, he now spent by far the most
enjoyable period of his university career. The intellectual atmosphere
of Berlin was quicker and less pedantic than that of Göttingen, and
he plunged into his studies with considerable energy.
In 1821 Heine published the first volume of his poems, containing
the Dream Pictures, some miscellaneous juvenile poems, and the
Lyrisches Intermezzo, which was inspired by the banker's, in the
same way that the Dream Pictures had been inspired by the
executioner's, daughter.
The book was an immediate success, how great may be gauged by
the numerous parodies and imitations which it almost
instantaneously evoked. It was at this period that he wrote the two
romantic tragedies of Ratcliff and Almansor. Both failures and devoid
of much merit, they served none the less useful purpose of
advertising his fame.
In 1823 we see an echo of his passion for Amalie in his love for his
younger cousin Therese, who seems in many respects to have been
a replica of her elder sister. Therese, however, refused to be
anything more than a cousin to him, and his heart was still further
embittered as is shown by the poem:
"Wer zum erstenmale liebt
Sei's auch glücklos ist ein Gott
Aber wer zum zweitenmale
Glücklos liebt, er ist ein Narr
Ich, ein solcher Narr, ich liebe
Wieder ohne Gegenliebe;
Sonne, Mond und Sterne lachen
Und ich lache mit und sterbe."
In 1824 he decided to prosecute his studies for his doctorial degree
with greater seriousness, and leaving behind him the distractions of
the capital, went back once more to the more staid and prosaic
Göttingen.
Heine intended not merely to take a degree for the sake of
ornament, but also to practise seriously as a lawyer. How serious
were these intentions may be seen from the fact that he went to the
length of paying in advance the heavy entrance fee which the legal
profession then exacted from Jews, and became baptized "as a
Protestant and a Lutheran to boot" on June 28, 1825.
Heine's conversion has frequently been criticised with superfluous
harshness. Let him, however, explain his position for himself:

"At that time I myself was still a god, and none of the positive
religions had more value for me than another; I could only wear
their uniforms as a matter of courtesy, on the same principle
that the Emperor of Russia dresses himself up as an officer of
the Prussian Guard when he honours his imperial cousin with a
visit to Potsdam."

After all, his apostasy brought with it its own punishment, not only in
its deep-felt shame, but in the fact that he eventually threw up law
for literature, and thus rendered so great a sacrifice of racial loyalty
and his own self-respect consummately futile. After selling his
birthright he found that he had absolutely no use for the mess of
pottage which he had purchased.
In the summer of 1825, Heine, having just succeeded in passing his
degree, proceeded to the little island of Norderney, off the coast of
Holland, to recuperate. Living ardently the simple life and indulging
to the full his passion for the sea, he now wrote not only the second
part of the Reisebilder, entitled Norderney, but the far greater
Nordsee Cyklus, which in its irregular swinging metre expresses with
such marvellous efficiency the whole roar and grandeur of the
ocean. Speaking generally, of course, Heine was too subjective to be
a real nature poet. No writer, it is true, fills up so freely and with so
fantastic an elegance the blank cheques of nightingales and violets,
lilies and roses, stars and moonshine, yet none the less these rather
served to grace his measure than as his real flame. His one genuine
love was the sea. With the sea he felt a deep psychological affinity.
The sea was the symbol of his own infinite restlessness, of his own
divine discontent, and mirrored in the sea's ever-changing waters he
beheld the incessant smiles and storms of his own soul.

"I love the sea, even as my own soul," he writes. "Often do I


fancy that the sea is in truth my very soul; and as in the sea
there are hidden water-plants that only swim up to the surface
at the moment of their bloom and sink down again at the
moment of their decay, even so do wondrous flower-pictures
swim up out of the depths of my soul, spread their light and
fragrance, and again vanish."

In 1826 Heine published the Heimkehr, the Nordsee Cyklus, the airy
and sparkling Harzreise, and the first part of the Reisebilder.
From Norderney Heine moved to Hamburg, avowedly to practise,
though it does not appear that he took his profession with much
seriousness. At any rate, until 1831, when he migrated to Paris, his
career is excessively erratic. At one moment he is paying a flying
visit to England, "the land of roast beef and Yorkshire plum-pudding,
where the machines behave like men and the men like machines"; at
another he is on the staff of the Allgemeinen Politischen Annalen
and the Morgenblatt of Munich; he is now in Hamburg, now in
Frankfurt, and now in Italy, where his sojourn inspired the racy and
brilliant Italy and Baths of Lucca, both of which works obtained the
gratuitous and well-merited state advertisement of prohibition, and
achieved a most undeniable succès de scandale.
The departure to Paris marks an entirely new epoch in Heine's life,
and offers a convenient stopping-place at which to give some
account of his early poetry and prose, as exemplified in the Book of
Songs, which was published in 1827, and the Reisebilder, the last
part of which, the Baths of Lucca, was published in 1831.
Though neither the Book of Songs nor the Reisebilder is as great or
as characteristic as the Romanzero and Poetische Nachlese on the
one hand, or the Salon on the other, they are yet by far the most
popular of his works and contain some of his most delightful writing.
One of the first traits that strikes us in the Book of Songs is the
Romantic tendency to bizarre and exotic themes. In the Junge
Leiden and Lyrisches Intermezzo in particular we move in a ghostly
atmosphere of apparitions, sea-maidens, skeletons, and midnight
churchyards. Another interesting characteristic of these poems is his
deep love of the East, a love which is to be probably ascribed more
to the general eastward gravitation of the Romantic school than to
the poet's Oriental blood. This tendency is responsible for two of the
most charming poems in the book, the exquisite lyric starting:
"Auf Flügeln des Gesanges
Herzliebchen trag ich dich fort
Fort nach den Fluren des Ganges
Dort weiss ich den schönsten Ort."

"Dort liegt ein rotblühender Garten


Im stillen Mondenschein;
Die Lotosblumen erwarten
Ihr trautes Schwesterlein."
And—
"Ein Fichtenbaum steht einsam
Im Norden auf kabler Höh',
Ihn schläfert; mit weisser Decke
Umhüllen ihn Eis und Schnee.
Er traumt von einer Palme,
Die fern im Morgenland
Einsam und schweigend trauert
Auf brennender Felsenwand."
This latter poem in particular illustrates admirably the vague melting,
infinite yearning which Heine at first experienced as deeply as did
any of the Romanticists. There are not wanting, however, and
especially towards the end of the book, examples of his later
manner, of that note of rebellion which he was afterwards to strike
with such inimitable precision. Occasionally his wistful pessimism
suddenly changes into cynicism, and in reaction from his morbid
sensitiveness he derives a sardonic satisfaction from probing his own
wounds as in the already quoted "Wer zum erstenmale liebt," while
in the mock-heroic Donna Clara and in the Frieden we see that
artistic use of the anti-climax of which he was afterwards to acquire
an even greater mastery. Even in the comparatively early Lyrisches
Intermezzo we see him constantly playing on that contrast between
the Real and the Ideal, between Dream Life and Waking Life, which
formed so integral a part of his subsequent life-outlook. Speaking
generally, however, the Book of Songs exhibits the sentimental
rather than the cynical side of Heine's mind. It possesses moreover
those qualities which remained in Heine throughout his life, the light,
airy touch, the intimate personal note, the delicate lyric sweetness,
and that concision which is found in poetry with such extreme rarity.
Let us turn now to the Reisebilder. Its most dominant characteristics
are its inimitable swing and the absolute irresponsibility of its
transitions. The grave, the gay; the lively, the severe; the sublime,
the ridiculous; the reverent, the frivolous; the refined, the crude; the
poetic, the obscene, all jostle pell-mell against each other in this
most fascinating of literary kaleidoscopes. It is no mere guide-book,
this record of his wanderings in the Harz, in Norderney, in England,
and in Italy, but rather a description of those reflections on men and
things which were suggested by his various adventures. In style the
Reisebilder marks a new epoch in German prose, or, as has been
said, showed for the first time since Lessing and Goethe that such a
thing as German prose really did exist. Heine was the first to show
convincingly that a Gallic grace and flexibility could be imparted into
the cumbrous and heavy-footed Teutonic language.
Psychologically the most interesting part of the Reisebilder is the
fervent Napoleonic worship which, combined with his love of liberty
and revolt against reaction, largely contributed to mould his life. The
general tone, moreover, of political, sexual, and religious freedom
that characterises the latter part of the Reisebilder rendered Heine
not a little obnoxious to official Germany, not only because of the
intrinsic heresy of the sentiments themselves, but of the joyous
rollicking insolence with which they were paraded.
It is small wonder, then, that the Paris July Revolution of 1830 made
the poet feel "as if he could set the whole ocean up to the very
North Pole on fire with the red-heat of enthusiasm and mad joy that
worked in him," and that in the spring of 1831 he migrated finally
and definitely from Germany to Paris.
This migration to Paris marks the turning-point in Heine's life. His
career in Germany had throughout been erratic, unsatisfactory, and
hampered by political restrictions. In Paris he settled down, felt that
now at last he was in a congenial element, and—found himself. It
was at Paris that he wrote his most brilliant prose and found
inspiration for his highest poetry, that he experienced his wildest
joys and his intensest sufferings. The first ten years of his sojourn
were probably the happiest in his life. His increased literary and
journalistic earnings helped to solve the financial problem, while
socially he was, as always, a pronounced success. He soon found his
way into the centre of the artistic set of the capital, and was on a
footing of intimacy with such writers as Lafayette, Balzac, Victor
Hugo, Georges Sand, Théophile Gautier, Michelet, Dumas, Gérard de
Nerval, Hector Berlioz, Ludwig Borne, Schlegel, and Humboldt. In
social life Heine's most characteristic feature was wit—a wit so
irrepressible as to burst forth impartially on practically all occasions,
and to resemble that of the Romans of the early Empire, who
preferred to lose their heads rather than their epigrams. Yet in
private life he was a devoted son and brother, an ideal husband. The
correspondence which he maintained up to his death with his sister
Lotte and his mother show conclusively what stores of German
Gemut he treasured in his heart. Particularly significant is the fact
that during the whole eight years in which he languished in his
mattress-grave he assiduously concealed from his mother the real
state of his health. Yet none the less "he could hate deeply and
grimly with an energy which I have never yet met in any other man,
but only because he could love with equal intensity," writes the
poet's friend, Meissner. Heine disapproved on principle of swallowing
an injury; when he was hit, he hit back. Not infrequently, as in his
rather scandalous attack on Börne, he would riposte with somewhat
superfluous efficiency, though according to his own theories it must
have been after all only a mistake on the safe side.
"Yes," writes Heine, "one must forgive one's enemies, but not until
they have been hanged."
Heine's quarrel with Börne originally arose out of the abomination
with which Börne, who was Radical to the point of fanaticism,
regarded the somewhat poetic and elastic Liberalism of his fellow-
Jew, and it is instructive to enter into an examination of the depth
and strength of those views which supplied the real motive power
which drove him from Germany to France. There can be no doubt
that Heine himself took his Liberalism with perfect seriousness. "In
truth I know not," he writes, "if I merit that my coffin should be
decorated with a laurel wreath. However much I loved Poesy, she
was ever to me only a holy toy or a consecrated means for heavenly
ends. It is rather a sword that they should lay on my coffin, for I was
a brave soldier in the Liberation War of Humanity." It should be
observed, however, that this Liberal had the most aristocratic
contempt for the uncultured δημος, as is shown by passages such as
the following: "The horny hands of the Socialists who will unpityingly
break all the marble statues which are so dear to my heart"; and, "If
Democracy really triumphs, it is all up with poetry."
Yet there can be no gainsaying that Heine's political orthodoxy was
perfectly unimpeachable on that anti-clericalism which has always
been one of the most cardinal points of Continental Liberalism.
He is rarely tired of tilting at Catholicism, and while he regarded
ascetic mediæval Catholicism as the vampire which sucked the blood
and light out of the hearts of men, he dubbed the modern Catholic
reactionaries in Germany "the Party of lies, the ruffians of
Despotism, the restorers of all the folly and abomination of the
Past."
Yet, if his beliefs were too wide to admit of the narrowness of a
consistent partisanship, his enthusiasm was deep and sincere for the
joy, light, and liberty of a new era that was to sweep away all the
unhealthy and plaguy humours of that blind, delirious, and anæmic
mediævaldom, which, to use his own phrase, has spread over the
countries like an infectious disease, till Europe was but one huge
hospital. Politically, in fine, Heine is a brilliant freelance, who, too
proud to wear the uniform of party, none the less fought valiantly for
the army of Progress and Humanity, a forlorn outpost in the War of
Freedom.[1]
Heine's polemical modernity manifested itself most efficiently in the
Deutschland, which, together with its sequel, The Romantic School,
was issued as a counter-blast to Madame de Staël's work of the
same name. This history of the religion, literature, and philosophy of
Germany is the masterpiece of Heine's extant prose. An academic
philosophic treatise, of course, it neither is nor professes to be. As a
description half-serious, half-flippant, however, of the main currents
of modern and mediæval Germany by a writer who sees life from the
bird's-eye view of the combined poet, journalist, thinker, and man of
the world, it is unrivalled. It contains some of Heine's loftiest and
most sublime flights, some of his most brilliant and trenchant
epigrams.
Particularly happy is the comparison drawn between the furious
onslaughts made by the French Revolutionists under Robespierre
and the German philosophers under Kant on respectively the divine
rights of kings and the divine rights of God.
How delicious is the conclusion of the parallel between the two men:
"Each eminently represents the ideal middle-class type—Nature had
decreed that they should weigh out coffee and sugar, but Fate willed
that they should weigh out other things, and in the scales of the one
did she lay a King and in the scales of the other a God....
"And they both gave exact weight."
As, however, has been previously pointed out, Heine's chief
characteristic as a prose writer is that marvellous elasticity which can
rebound from the frivolous to the sublime with the most
consummate ease and celerity. Interspersed with the bright flash-
light of the epigrammatic pyrotechnics lie really great passages, and
pieces in particular like those on Luther and Goethe possess the
clear golden ring of the grand style.
Heine's political ideals were subjected to the inevitable
disillusionment. The Revolution of July, which he had fondly hoped
would complete the work of the great movement of 1793, merely
resulted in the anti-climax of the establishment of a bourgeois
constitution under a bourgeois monarch. He tended to become
generally embittered. Money matters, too, began to irritate him, and
his health to give him trouble, and though he found a devoted sick-
nurse in Matilde Crescenzia Mirat, a grisette whom he married in
1841, the lady with whom "he quarrelled daily for six years in that
life-long duel at the termination of which only one of the combatants
would be left alive," yet none the less his condition began to
deteriorate. "The damp cold days and black long nights of his exile"
oppressed him, and he began to yearn for the old German soil. He
gratified his Heimweh by a flying and surreptitious visit to Germany
that inspired the well-known Germany or a Winter Tale, which,
together with the somewhat similar Atta Troll, constitutes his most
sustained poetic achievement. These two poems are about as
characteristic as anything which he wrote. They represent admirably
his wild classic Dionysiac fantasy, his sudden dips from the most
extravagant Romanticism to the harsh, crude facts of reality, the
marvellous swing and sweep of his Aristophanic humour.
Very typical is the following satire on the intimate relation between
anthropo- and arctomorphism.
"Up above in star-pavilion,
On his golden throne of lordship,
Ruling worlds with sway majestic,
Sits a Polar bear colossal."

"Stainless, snow-white shines the glamour


Of his skin, his head is wreathed
With a diadem of diamonds,
Flashing light through all the heavens."

"Harmony rests in his visage,


And the silent deeds of thought,
Just a whit he bends his sceptre,
And the spheres they ring and sing."
The above quotation shows excellently the essentially poetic quality
by which Heine's wit is illumined. A satirist as keen and vivid as
Voltaire, he possesses all the logical aptness of the Frenchman
without his dryness. His chief characteristic, in fact, is the method by
which in his imaginative flights he combines the maximum of this
logical aptness with the maximum of humorous incongruity. No
humorist dives for his metaphors into stranger water or brings up
from the deep more bizarre and fantastic gems. A charming example
of Heinean humour is the following passage from one of his
prefaces: "A pious Quaker once sacrificed his whole fortune in
buying up the most beautiful of the mythological pictures of Giulio
Romano in order to consign them to the flames—verily he merits
thereby to go to heaven and be whipped with birches regularly every
day."
One of the most cardinal traits of Heine's wit and humour is a
phenomenal freedom of tone and language, a freedom that is
occasionally not always in the most unimpeachable taste. Heine, in
fact, is a writer who admits the public gratis to his psychological
toilette, where he exposes with studied recklessness his most private
thoughts. This question cuts too deep into Heine's life-outlook to be
lightly passed over, and necessitates some examination. In the first
place even Heine's most enthusiastic admirer will admit that a great
deal of this licence is sheer gaminerie; Heine is the mischievous
schoolboy of literature who thoroughly revels in being naughty,
grimacing by an almost mechanical instinct, so soon as he catches a
glimpse of the sacred figures of religion and sex. Like Baudelaire, he
loves, almost indeed as a matter of conscientious principle, to make
the hairs of the philistines stand on end. His one excuse, however, is
that even when he causes the hairs of the philistines almost to
spring from their roots, as indeed he does not infrequently, he
conducts the operation with so light a touch, so exquisite a grace,
that the offence is almost redeemed. Let him speak in his own
defence, in the lines from the great Jewish poem, "Jehudah Halevy":
"As in Life so too in poetry
Grace is aye Man's highest Good;
Who has grace, he never sinneth
Not in verse nor e'en in prose."

"And by God's grace such a poet


Genius we do entitle,
King supreme and uncontrolled
In the great desmesne of thought."
Not unnaturally his coarseness grew apace with the virulence of his
disease, and he himself explains his cause to his friend "La Mouche":
"Vois-tu c'est la faute de la mort qui arrive à grands pas, et quand je
la sens ainsi tout près de moi comme à present j'ai besoin de me
cramponner la vie ne fût ce par une poutre pourrie." This final phase
in fact was simply a reaction against his fate, and is not altogether
without analogy to that same psychological principle which dictated
much of the crude buffoonery of Swift and Carlyle by way of an
heroic protest against their own helplessness.
Far more important, however, is the fact that this particular trait of
Heine is profoundly symbolic of his outlook on life, especially where
an obscene jest marks the climax of a genuinely poetical flight.
Circumstance turned him into a cynic, who saw frequently in Liberty
but the uprising of a squalid proletariate, who heard in the "sweet
lies of the nightingale, the flatterer of spring," merely the
"harbingers of the decay of its queenliness," and who beheld in love
but a mere illusion of the senses that vanishes so soon as the
beloved one utters a syllable. Held fast in the grip of the great
World-paradox, Heine is forced to look at life as a glaring
phantasmagoria of blacks and whites, in which the sublime and the
ridiculous, the pathetic and the grotesque, the refined and the
crude, dance along hand in hand till they become so confused that it
is impossible for the observer to distinguish the individual partners,
and he is reduced to describing, in pairs, the giddy, whirling couples
that make up the fantastic medley.
This incessant antithesis makes Heine one of the most complete of
modern writers.
The poet's world is composed of two hemispheres: one is the abode
of the beautiful, the grand, the tragic; the other of the ugly, the
petty, the comic. Most poets confine their efforts to only a small
portion of one of these hemispheres. Heine, however, is the Atlas of
poetry, who supports both of the half-spheres of the world, and who,
by way of proving how easily his burden sits upon him, suddenly
turns juggler, and after showing his audience one side of the magic
globe, will, hey presto! whisk the whole world round, and before
they know where they are smilingly confront them with the other.
In 1848 the spinal affection from which he suffered became so acute
that Heine was compelled to take to that mattress-grave where,
paralytic and half-blind and racked intermittently by the most
agonising spasms, he dragged out the eight most ghastly years of
his life. At first the death-chamber was one of the favourite
rendezvous of fashionable Paris, but as the novelty wore off, his
circle of friends grew narrower and narrower, until eventually a visit
from Berlioz seemed only the crowning proof of the musician's
inveterate eccentricity.
Heine, however, rose manfully to the occasion, and did all that he
could under the circumstances. Always a passionate lover of the
paradoxical, he now began to appreciate with an intense and
unprecedented relish the infinite humour of the great Life-farce, one
of the most effective scenes of which was even now being enacted
in the person of the poet of joie de vivre, who, enduring all the
agonies of the damned, lay dying in La Rue d'Amsterdam to the
quick music of the piano on the story underneath, while only a few
feet away shone all the glow and glitter of Parisian life.
The chief occupation and solace of the dying man was the writing of
his Memoirs, the great Apologia pro vitâ suâ which was to square his
accounts with the world, and win for him the future as his own.
Yet at times the greatness of his sufferings would soften his heart.
He would find in the Bible the magic book which had power to dispel
his earthly torments; the "Heimweh for heaven" would fall upon him,
and again would he know his God. It would seem, however, that
Heine's death-bed reconversion is simply to be regarded as one of
the numerous instances of the Prince of Darkness exhibiting
monastic proclivities under the stress of severe physical malaise. For
eight years Heine lay a-dying, and with the skeleton of Death
assiduously serving the few bitter crumbs that yet remained of his
feast of life, he was, as a simple matter of pathology, almost bound
to believe once more, even if he had been the most hardened infidel
in existence. Heine, however, was no cynical atheist. The current
religions, it is true, he considered pretty poetry, but bad logic, yet
none the less he was genuinely imbued with the ethical idea.
"I am too proud," he writes, "to be influenced by greed for the
heavenly wages of virtue or by fear of hellish torments. I strive after
the good because it is beautiful and attracts me irresistibly, and I
abominate the bad because it is hateful and repugnant to me."
What, in fact, served Heine in the stead of a theology was his fervid
enthusiasm for Progress and Humanity. His real religion was the
religion of Freedom, the religion of the poor people, the new creed
of which Jean Rousseau was the John the Baptist and Voltaire the
chief apostle; Heine's Madonna was the red goddess of Revolution,
who exacted from her worshippers innumerable hecatombs of
human victims; the Man-god whom he revered as the Saviour of
Society was Napoleon, the Son of the Revolution, the drastic
reorganiser of the world, who, unappreciated by the pharisees and
reactionaries of his time, and finding his Golgotha on the "martyr-
cliffs of St. Helena," endured for more than five years all the agonies
of a moral crucifixion; while to complete our version of the
Heinesque theology, his Heilige Geist was the Holy Spirit of the
Human Intellect which he says "is seen in its greatest glory in Light
and Laughter," and the Revelation which inspired him most deeply
was, to use once more his own phrase, "the sacred mystic
Revelation that we name poesy."
It is interesting to trace the influence of these last ghastly years on
Heine's writings. His almost complete physical prostration brought
with it its own compensation in the shape of a marvellous psychic
exaltation, and the Romanzero and the Poetische Nachlese contain
some of his greatest and most moving poems. Nowhere do we see
more clearly his most characteristic excellences, his delicacy, his
power of antithesis, his concision.
It is Heine's compression, in fact, which is one of the most
pronounced features of his poetic style. The whole quintessence of
joy and pain, of love and sorrow, is frequently distilled into one short
poem. This Heinesque condensation is a variant of the same theory
that can be traced in the old Impressionist school of painters which
is concerned with the outline and the proper light and shading of the
outline to the exclusion of minor details, and in the journalistic cult
of the "story" in which the ideal aimed at is "the point, the whole
point, and nothing but the point." Heine, in fact, is unique among
the poets for narrating a tale with the minimum of space and the
maximum of effect, for narrating it in such a way that each line
serves to heighten the level of intensity, till at length the edifice is
crowned by the climax. This feature of his style is well illustrated by
the end of the frequently quoted poem, "The Asra," in the
Romanzero:
"And the slave spake, I am called
Mohammed, I am from Yemen,
And my stock is from those Asras,
They who die whene'er they love."
Though, moreover, he protested to the last against his fate, his tone
in the Romanzero and the earlier Poetische Nachlese is more mellow
than in his earlier writings. His cry from the heart is not the cry of
defiance but rather of the pathetic wistfulness of impotence. Yet
before the candle of his life became extinguished it leapt up in one
final flicker, the most marvellous of all. A characteristic caprice of
fate made him acquainted during the last months of his life with his
one true soul-affinity, the charming woman who is known under the
pseudonym of Camille Selden or La Mouche.
Is it then to be wondered at that when the rich feast of a perfect
love, for which he had craved Tantalus-like all his life, was offered to
him almost at the very minute that his lips were being sealed by the
cold kiss of death, the whole soul of the man should leap up in
indignant protest, and that such poems as "Lass die heiligen
Parabolen," and the even more wonderful series of stanzas with the
refrain, "O schöne Welt du bist abscheulich," should exhibit the cold
insolent shrug of the man convinced of the righteousness of his plea
that of all the places in the universe this human earth "where the
just man drags himself along beneath the blood-stained burden of
his cross, while the wicked man rides in triumph on his high steed,"
is the most iniquitous?
Heine died at four o'clock in the morning of February 17, 1856. He
was buried by his own directions in Montmartre, "in order to avoid
being disturbed by the crowd and bustle of Père Lachaise."
His writings form an incessant stream of paradoxes, but his life is the
greatest paradox of all. The prophet of the new religion of liberty, he
was repudiated by his country, and his happiest days were spent in
the land of exile; throughout his life he sought for love, to live years
of the most healthy prosaic domesticity with his mistress, and to find
his one true romance on his death-bed; he imagined that he was a
great political force, but it is rather as a poet that he survives; as a
poet his chief theme was the Joy and Light of Life, and he drew his
truest inspiration from the darkest depths of his agony; even as a
great writer he has been chiefly known by the comparatively inferior
Book of Songs and Reisebilder, while his masterpiece, the Memoirs,
the great highly barbed Parthian arrow shot from the grave to
transfix his enemies for all eternity, lay mouldering for many years
amid the dusty archives of the Vienna Library.
His message, too, the core and kernel of his philosophy, is again a
paradox. To the sphinx-like riddle with which every thinker is
confronted, "Is Life poetry or prose, tragedy or farce?" Heine made
answer that the pathos and poetry of life were contained in the fact
that life was so essentially grim and unpoetical, and that the real
tragedy of the world lay in the ghastly farce of it all.
[1] Cf. the poem "Enfant perdu," beginning "Verlorner Posten in
dem Freiheits Kriege."

THE PSYCHOLOGY OF DISRAELI

The recent centenary of the birth of Benjamin Disraeli renewed our


interest in the most striking figure in the English history of the last
century. Throughout his life Disraeli made it an important part of his
métier to be interesting, and it is certainly a convincing proof both of
his great natural fascination and of the adroitness with which he
worked his pose, that even beyond the grave his character should
still exercise our curiosity and blind us with the various facets of its
brilliancy. He fairly bristles with paradoxes, this cynic, who was also
a sentimentalist, this Oriental mystic, who was one of the most
finished dandies in London, this shameless adventurer, with his
pathetic and chivalrous devotion to his sovereign, this political Don
Juan, who provided a classic example of conjugal affection. Many
have essayed to solve the riddle of the "Primrose Sphinx"; but the
best testimony to their almost universal failure is that nearly every
biographer has produced a completely different version of his
character. Mr. Hitchman, "one of the helpless, somnambulised cattle
whom he led by the nose," to use Carlyle's phrase, portrays him (in
The Public Life of the late Lord Beaconsfield) with charming naïveté
as the "disinterested and patriotic statesman." Mr. T. P. O'Connor, on
the other hand, who, when still sowing his literary wild oats, painted
Disraeli even blacker than the Prince of Darkness himself, in a book
unworthy of any serious biographer, simply overshoots the mark.
Froude, in his Life, comes nearer to the truth, but is hampered by
being forced to compress the history of a crowded life and the
psychology of a complex character into a narrow and inadequate
compass. Both Froude, however, and Mr. Sichel, who has given us an
interesting volume on Disraeli's personality, lay too much stress on
his imaginative and idealistic features.
The reason for this inability to comprehend a character, in many
respects singularly typical of his age, lies not so much in the alleged
inadequacy of the materials as in the incapacity of most English
writers for handling general ideas. The English mind is too concrete
for social psychology; it delights in the almost mechanical work of
classifying animals, but fails to produce any classification of
characters worth the name. The Disraeli problem is admittedly
difficult; the secrecy which until recently kept us from all knowledge
of the greater portion of his papers and correspondence is
undoubtedly a handicap, but the difficulty is by no means
insuperable, nor the material so scanty as is usually supposed. Let
us take Disraeli in relation to his age, his environment, his ancestry,
then what would otherwise have struck us as strange, not to say
impossible, stands out clear and inevitable. Another valuable source
of information is to be found in his novels, though it is always
difficult to discriminate between what is and what is not
autobiographical in these works.
A vigorous and imaginative mind, when writing about its own
history, will naturally not stint itself in its licences; it will abandon
itself to all kinds of hypotheses; it will take a certain phase of itself,
frame circumstances to suit its development, and proceed on the
fictitious assumption; it will indulge freely both in caricature and
idealisation. In Vivian Grey, for instance, Disraeli has slightly
exaggerated the more cynical side of his nature; Sidonia, on the
other hand, is an idealised version of Disraeli; it is Disraeli raised to a
higher power; it is what he would have liked to have been, but was
not, any more than the actual Byron was as brave, as romantic, and
as fascinating as the ideal Byron who is portrayed in Conrad, Childe
Harold, and Don Juan.
Yet, none the less, Sidonia, Fakredeen, Vivian Grey, and Contarini
Fleming possess a strong family likeness, and strike a genuine
autobiographical note. With regard to the two latter, Mr. Sichel, in his
study of Disraeli, is unwarranted in his attempted depreciation of
their evidence, on the theory that they represent merely a distorted
and transient phase of Disraeli's development, to be ascribed to ill-
health and immaturity. On the contrary, the contortions of great men
in adolescence are peculiarly instructive. It is then that the very
elements of the future man are fermenting in the crucible; and is not
growth more significant than maturity? It is not a paradox, but a
fundamental truth, to say that a man is never more himself than
when he is not himself; it is in periods of violent upheaval that the
conventional superstructure is destroyed and the innermost
foundations of character are laid bare. It is far easier to tone down
than to touch up, and the unrestrained sincerity of these early
novels, written under the impetus of intense emotion, throws far
more light on Disraeli's real character than a book like Endymion, the
official pronouncement of his maturer years. A prudent use, then, of
the novels, and an examination of his relations to his age,
environment, and ancestry should enable us to construct a
psychology of Disraeli that should be at once convincing and
consistent, and adequate to shed light on many of the obscure
points of his character.
The Sturm und Drang age of the Revolution in which Disraeli was
born marked the passing of Europe from childhood to manhood,
from mediævalism to modernity. Like all transition periods, it was
peculiarly complex; the tendencies being so varied, and were so
frequently accompanied by the reactions against themselves, that it
requires considerable care to disentangle the principal threads.
It was an age of progress where reaction was frequently to be seen
at work; it was an age significant for a violent outburst of scientific
materialism, and the consequently inevitable mysticism of a religious
revival. It was an age at once scientific and romantic, individual and
cosmopolitan. It was an age where circumstances produced strange
mixtures, so that in England we are brought face to face with the
paradox that Gladstone, the founder of democratic idealism,
obtained his seat under the old system of close boroughs, while
Disraeli, the most brilliant example of the new democratic theory of
la carrière ouverte aux talentes, found his way to power as the head
of the aristocratic and conservative party. The predominant note,
however, was one of democratic individualism. With the French
Revolution the yoke of responsibility, political and religious, was
violently thrown off; new and wide fields had been opened out to
commerce by the extended communications and the new mechanical
inventions. A quickened life broke in upon the lethargy of the
previous century. The struggle for existence entered on a sharper
and intenser phase. Ambitious men vehemently dashed themselves
against the social barrier, which day by day became more easy to
climb. In every department it was the age of the clever and
ambitious parvenu. In war and in politics Napoleon, in poetry Burns,
in fiction Balzac, give convincing testimony to the power of the new
regime. It was the age of the French Revolution and of the Holy
Alliance, of Condillac and of Chateaubriand, of Laplace and of
Shelley, of Godwin and of Tom Paine.
But equality is a medal with two faces: on the one side is written, "I
am as good as, if not better than, everyone else"; on the other,
"Everyone else is as good as, if not better than, myself." The first
was the motto of the rampant individualism and vigorous national
policy of Disraeli, the latter of the hesitating Christian spirit and
sentimental cosmopolitanism of Gladstone. Gladstone, indeed, is
such an excellent foil to Disraeli that we may well be permitted the
following quotations, where the rift in Gladstone's lute, between the
churchman and the politician, stands in pointed contrast to the unity
of purpose that from his earliest years actuated his rival. Gladstone,
torn between his missionary impulse and yearning for apostolic
destination on the one hand, and healthy ambition on the other,
writes to his father: "I am willing to persuade myself that in spite of
other longings, which I often feel, my heart is prepared to yield
other hopes and other desires for this: of being permitted to be the
humblest of those who may be commissioned to set before the eyes
of man the magnanimity and glory of Christian truth. Politics are
fascinating to me, perhaps too fascinating. My temper is so excitable
that I should fear giving up my mind to other subjects, which have
ever proved sufficiently alluring to me, and which I fear would make
my life a series of unsatisfied longings and expectations." Disraeli is
less undecided, as is clear from the following quotation from
Contarini Fleming: "I should have killed myself if I had not been
supported by my ambition, which now each day became more
quickening, so that the desire of distinction and of astounding action
raged in my soul, and when I realised that so many years must
elapse before I could realise my ideal, I gnashed my teeth in silent
rage and cursed my existence," Disraeli will give up anything rather
than his chance of being a great man. At a time when most clever
young men of his age were thinking of a scholarship he had finally
decided to go in for a premiership. He has planned his campaign, he
will fool the world to the top of its bent. When yet a boy Disraeli
says, as Vivian Grey: "We must mix with the herd, we must
sympathise with the sorrow that we do not feel and share the
merriment of fools. To rule men we must be men, to prove that we
are strong we must be weak. Our wisdom must be concealed under
folly, our constancy under caprice."
None the less, Disraeli had too vivid an imagination, too keen a
sense of the picturesque, not to be affected to a certain extent by
the current Romanticism. We see this in the Eastern novels of
Tancred and Alroy, also in Contarini Fleming, the English Wilhelm
Meister, which exhibits the weaker and more morbid side of the
author's character, and is a useful supplement to Vivian Grey. But it
is the latter, however, who represents most accurately the ideals and
aspirations of the young Disraeli, and, taken generally, is a broad
adumbration of his subsequent career. But the Disraeli of Vivian Grey
was not so unique as is usually considered, and an analogy between
him and the celebrated Frenchman, who wrote a novel about the
same period, and one, moreover, singularly typical of his age, proves
instructive. Benjamin Disraeli and Henri Beyle were in all superficial
details so absolutely different that one might well hesitate before
making the comparison, yet they were radically similar in many of
their larger outlines, and in particular their characters, as revealed in
the heroes of two novels, Vivian Grey and Le Rouge et le Noir, show
an extraordinary resemblance. Both Julien Sorel and Vivian Grey are
impelled by a violent and overwhelming ambition; both, originally
excluded by their status from participation in the great prizes of the
world, set out undaunted to conquer, the one as a priest, the other
as a politician. Cynical, with that extreme and savage species of
cynicism which is the reaction from intense sensitiveness, they both
wage war on society in their passion for success, while the nobler
and more generous instincts with which nature had endowed them
perish in the struggle.
But this Time-Spirit of individualism was no mere cold-blooded
philosophy of egoism. It was, after all, an age of genuine poetry, of
fresh ideals. The halo of romance played around the most
abandoned sinners. Individualism found, in addition, an æsthetic
sanction, as was seen in the prodigious vogue of Byron, where the
picturesque pose of the one man pitted against society appealed
strongly to the popular imagination. How deeply Disraeli was imbued
with Byronism is evidenced not only by the whole tone and manner
of his early life, but by his resuscitation of the Byronic legend in
Venetia.
This spirit of combined idealism and intense practical energy is met
with again in Disraeli's race and ancestry. The Jewish race is a
compound of materialism and idealism. The Jew is the dreamer in
action, combining fluid imagination with adamantine purpose. These
two phases of the Jewish character are seen excellently in Disraeli's
father and paternal grandfather. The latter, an Italian Jew, came over
to England about the middle of the eighteenth century, and quickly
made a fortune by dint of his shrewd business talent and fixity. His
son Isaac was gifted with an unfortunate superfluity of the poetic
temperament. His youth was erratic and unhappy, but when close on
thirty he found a secure refuge in the quiet waters of literature. To
his Semitic blood is also to be traced Disraeli's prodigious tenacity of
purpose. He came of a stiff-necked people, so that opposition
stimulated him, and his early failures served but to render sweeter
his eventual success. He had, too, the calculating foresight of the
Jew, and could pierce the future, if not with prophetic vision, at any
rate, with marvellous intuition. His Oriental strain of mysticism
served him in good stead. He never forgot that he was a scion of the
Chosen People, and came of a race which had never sullied its purity
of lineage by changing its blood. Was he not the chosen man of the
chosen race? Could he not read his future, if not in the stars, "which
are the brain of heaven," yet in his own brilliant and meteoric brain?
He had a full measure of the pride of race, and plumed himself to
the last on what he may well have called "the Oriental ichor in his
veins." If his enemies dubbed him a parvenu he would fling the
wretched taunt back in their faces, bidding them realise that they
came from a parvenu and hybrid race, while he himself was sprung
from the purest blood in Europe. How keen was this genealogical
Judaism we can see from the classic letter to O'Connell, where he
wrote that "the hereditary bondsman had forgotten the clank of his
fetters," and from his masterpiece of character-drawing, Sidonia,
who, with wealth, intellect, and power at his command, yet found
his chief "source of interest in his descent and in the fortunes of his
race." Disraeli's Judaism, however, did not extend to the religious
tenets of the creed. Few, no doubt, are the instances of a converted
Jew proving a genuine Christian, but Disraeli had too much of the
mystic in him to be an atheist, and if we take into account the
elasticity of his imagination, there is little reason to doubt that he
was at any rate reasonably sincere in his belief that Christianity was
merely completed Judaism, Calvary but the logical corollary of Sinai;
he would also, no doubt, find a malicious joy in reminding those who
taunted him with his origin, that "one half of Christendom worships
a Jew and the other half a Jewess." Anyway, the Christian religion
played nothing approaching an integral part in his life; while an
amiable acquiescence in its dogmas was, at the best, as it has been
with so many, but an intellectual habit. His Jewish origin helped him,
moreover, in that he approached the problems of politics with a mind
free from conventional British prejudices. He was never a thorough
Englishman, and was proud of the fact, instead of thanking God
"that he was born an Englishman," as do many of his race, who
betray in their every word and action their Jewish nationality. His
admirable expert knowledge of the English character was throughout
professional, not sympathetic.
When we turn to Disraeli's early environment, we find that it was
one calculated to foster both ambition and a literary imagination. He
breathed from his earliest days the atmosphere of books, and almost
from the cradle imbibed avidly the many volumes of Voltaire.
Nothing is so stimulating to the youthful mind as the unchecked run
of a library, with its delightful excursions into the unexplored country
of literature. His natural sensitiveness was hardened by his
experiences at school, where his nationality and cleverness rendered
him unpopular. The reaction intensified his already precocious
ambition, and gave him that consciousness of semi-isolation which
formed one of the chief parts of his strength. His ambition was
further heightened by the smart literary set which he met constantly
at his father's house, and his early glimpses of the great world.
Disraeli is palpably exaggerating when he says, apropos of Vivian
Grey, that "he was a tender plant in a moral hot-house," but the
following passage is significant:

"He became habituated to the idea that everything could be


achieved by dexterity, that there was no test of conduct except
success; to be ready to advance any opinion, to possess none;
to look upon every man as a tool, and never to do anything
which had not a definite though circuitous purpose."

It is this trait of doing things with an object which supplied the true
clue to Disraeli as a man of letters. We admit, of course, the verve
and brilliancy of the novels, their claim to rank as classic, but it is
impossible to arrive at a correct appreciation of them unless they be
taken in the closest conjunction with their author's political career.
Vivian Grey, for instance, no doubt afforded an excellent outlet for
the fermenting passion of Disraeli's youth; it was itself one of the
best society novels ever written, but it was something more. Before
that time the future Premier had been hiding his light. How could he
obtain a free field for the exercise of his gifts? His father's Bohemian
clique scarcely answered his purpose. How could he burst open the
doors of society? The bombshell was supplied by Vivian Grey. It was
a case of self-advertisement raised to the level of a fine art, and
Disraeli introduced himself to the public with a bow of most
elaborate flourishes. Contarini Fleming strikes a slightly different
note, exhibiting the more poetic side of its author's character; but
we must not forget that at the time when it was published Disraeli's
long absence in the East had temporarily obscured his fame in
London, and that it was the success of Contarini Fleming which
secured for him once more the entrée into society. Similarly,
Coningsby, Sybil, and Tancred were, in the main, but the gospels in
which, in the rôle of a political saviour, he propagated the new creed
of Young England. Lothair and Endymion were partly written to
replenish his empty exchequer. The protagonists, moreover, in all his
chief novels were fashioned in the image of himself, and even Lord
Cadurcis in Venetia, who is theoretically Byron, is portrayed with the
physical features of the author, so as to ensure a vivid impression on
the public mind of his own personality. Not that Disraeli did not
experience a genuine joy in the wielding of the pen. He could soar
high in his flights of mysticism and romance; could describe the
picturesque and the beautiful in passages of inspired rhetoric,
though it was in the dash and brilliancy of his satire which at its best
equalled that of Heine, or Voltaire, or Byron, that he was most
himself. His style is redolent of his race. It possesses the genuine
Oriental glamour, the Oriental love of gorgeous and grandiose
magnificence, the Oriental lack of symmetry and proportion. His
prodigious genius for sarcasm was also Semitic, if we are to believe
Mr. Bryce, who considers that gift a peculiar property of the race,
instancing, as examples, Lucian and Heine, the greatest satirists of
ancient and modern times.
This same combination of temperament and policy which explains
Disraeli, the man of letters, explains Disraeli, the dandy. Living as he
did in an age which revolted, under the leadership of Count D'Orsay,
against the chaste and classic traditions of Brummel, and which
offered in the elaborate picturesqueness of its dress an excellent
medium for the expression of personality, is it to be wondered at
that so ambitious a nature as Disraeli's should, apart from other
reasons, enter gaily into the sartorial arena? These early years
remind us of Alcibiades, who, in his youth, his genius, his precocious
political ambitions, his aristocratic lineage and superb insolence, his
extravagance and irresponsibility, offers a fairly close analogy.
Disraeli, however, was an Alcibiades with ballast, and his most erratic
phases were governed by a consistent purpose. He had, it is true,
the regular Hebrew love for the picturesque, the racial craving for
flamboyant display; but the unique characteristic of the man was the
ingenious method by which he exploited even his weaknesses to
advance his purpose. Realising that nothing was more fatal to his
career than the indifference of the public, that to be hated was
better than to be ignored, and that notoriety was a passable
substitute for fame, he was determined to bulk largely in the public
eye. Living, fortunately, in an age when dandyism, if not an art, was
at any rate a career, and when "wild, melancholy men" were still the
rage among the ladies, he manipulated the dandy and Byronic pose
with phenomenal success. But his social career was not all pose.
Though political ambition was to him always the main point of
existence, he was far too healthy to lose sight of the small change of
life. He had, moreover, a genuine love of society. His remark apropos
of Gladstone, "What can we do with a leader who is not even in
society?" was sincere in spite of being an epigram, and the hosts of
great ladies who crowd his novels attest conclusively to his social
fastidiousness. But the most convincing proof of this lighter side of
his nature is to be found in his correspondence with his sister. Those
letters, dashed off hurriedly to his "dearest Sa," written with that
complete lack of ceremony which is the sign of a perfect intimacy,
show with what zest he frequented balls and water-parties, dinners
and soirées. Yet his ambition is never far in the background. He goes
to the House of Commons, hears the big man speak, and then writes
to his sister, "But between ourselves I could floor them all." His
genius for conversation is historic, and we are not surprised that he
considered that the one unforgivable sin was to be a bore. He had
not, it is true, Gladstone's habit of unburdening himself freely to the
most casual of acquaintances. How many, indeed, were there of his
intimates who had penetrated into the secret places of his heart?
But over-much sincerity is a hindrance to the art of conversation;
and many of his most brilliant paradoxes were thrown off as an
evasive retort to an impertinent question. When, however, we come
to Disraeli's social and private life, the most interesting question that
presents itself is that of his relation to his wife. Even though he had
discoursed in Contarini Fleming of the grand passion with all the
high-flown sentimentalism of the age, it was obviously impossible for
him, considering the disparity of their ages, to be seriously in love
with Mrs. Disraeli; and it must have seemed that he had been forced
to exchange the poetry of the mistress for the prose of the wife. Had
he not, about ten years before his marriage, written to his sister,
"How would you like Lady B—— for a sister-in-law? Clever, £25,000,
and domestic. As for love, all my friends who have married for love
either beat their wives or live apart from them. This is literally true. I
may commit many follies, but never that of marrying for love, which,
I am convinced, cannot but be a guarantee of infelicity." Yet this
union, based originally on mere policy and camaraderie, was
eventually crowned with the most faithful of loves. It was his wife's
absorbing interest in his career that supplied the link. He has himself
written that the most exquisite moment in a man's life was when he
surprised his lady-love reading the manuscript of his first speech,
and the sympathy of Mrs. Disraeli in his successes may well have
given them a yet further charm. The situation is well expressed in
the remark of Mrs. Disraeli's: "You know you married me for money,
and I know that if you had to do it again you would do it for love."
In fact the warm and constant affection Disraeli lavished on his wife
during her lifetime, and the poignant grief that he evinced at her
death, furnish a more than sufficient refutation to those who persist
in regarding him as a mere cynical fortune-hunter. Disraeli, like
Browning, had
"Two soul sides, one to face the world with,
One to show a woman when he loves her."
In the other departments of private life he was likewise exemplary.
His hardness was limited to politics; he was the most dutiful of sons,
the most affectionate of brothers, the most faithful of friends. His
debts, for the most part, were incurred by backing the bills of other
men. His touching and romantic friendship for Mrs. Brydges
Williams, the eccentric old Cornish lady who gave him pecuniary
assistance at a critical period of his career, is well known. The story,
again, of the Premier and his wife dancing a Highland jig in their
night apparel on hearing of the success of an old friend, shows how
little the bitter struggles of politics had hardened his heart.
Particularly touching, also, is the mutual affection between him and
the Queen, that sweetened his last years. She was, as we read in a
letter of Disraeli's to the Marchioness of Ely, "the best friend he had
in the world."
But Disraeli, though he fulfilled himself in many ways, was first of all
a politician, and it is Disraeli the politician rather than Disraeli the
man of letters, the dandy, or the human being, that principally
provokes our interest. What were his real views on politics? How far
can we distinguish between the official edition of himself which he
displayed for public inspection and the original that he alone could
read? Given his policy, how far was it justifiable, how far rational?
The view of his most devoted, but yet in reality, quite
unappreciative, admirers, that throughout a political career of over
half a century he remained consistently and absolutely faithful to his
original ideals, and that he introduced into politics an integrity and
disinterestedness that Parliament had rarely witnessed, is even more
absurd than the opinion of his blind and malignant enemies that he
was a mere charlatan who juggled with parties and the people
without possessing a single genuine political faith of his own.
Disraeli, as was inevitable in a man of so detached and unprejudiced
a nature, simply took the then party system at its true worth, and, of
course, realised from the outset that before he could do anything
worth doing he must first obtain that power which alone could give
him the opportunity of doing it. His attack on Peel was, primâ facie,
an occasion that it would have been the depth of folly to have
missed, and Mr. Birrell's statement that Disraeli "ate his peck of dirt,"
and his comparison of him to Casanova, is mere petulance. For these
preliminary stages of the higher politics Disraeli was admirably fitted,
and the following autobiographic passages from Tancred show how
congenial were his Herculean labours: "To be the centre of a maze
of manœuvres was his empyrean, and while he recognised in them
the best means of success he found in their exercise a means of
constant delight"; and again, "'Intrigue,' cried the young prince,
using, as was his custom, a superfluity of expression both of voice
and hand and eyes, 'intrigue, it is life, it is the only thing. If you wish
to produce a result you must make a combination, and you call
combination intrigue.'" Disraeli viewed party politics from the
dispassionate standpoint of a chess-player, "playing off the proud
peers like pawns," skilfully manœuvring his knights and bishops
beneath the shadow of the old mediæval castles, though it was "in
his masterly manipulation of his queen" that he really surpassed
himself. What a contrast to Gladstone's youthful frame of mind, who
entered politics because he felt a strong moral duty to defend that
Church which he was afterwards partly to disestablish against the
insidious attacks of philosophic Radicalism. But Disraeli's point of
view was, after all, merely that which was obvious and rational. It is
well known that in Disraeli's day the whole efficiency of the party
system as a means of carrying on the government was based on
that sagacious inconsistency, so characteristic of this country, which,
cheerfully accommodating the most untractable of facts to the most
docile of theories, drew between the two parties no clear dividing
line either of principle or of class. Those genuine lines of cleavage
both of policy and interest that now tend to become more and more
clearly marked did not then exist. The only vital political distinction
then existing in England was that between the Ins and the Outs.
Whigs and Tories were, in their origin, merely the names for the two
rival organisations for the pursuit of political power into which the
oligarchy of the time had divided itself, and the party catch-words
then indicated as much essential difference as the badges by which
the two sides of a "scratch" game symbolise a fictitious distinction.
Particularly interesting is the following quotation from a letter of
Gladstone, written comparatively early in his career, which shows
convincingly that the subsequent democratic idealist fully realised
the intrinsic farce of the then party system: "Each of them, the Whig
and the Tory Party, comprises within itself far greater divergencies
than can be noticed as dividing the more moderate portion of the
one from the more moderate portion of the other. The great English
parties differ no more in their general outlines than by a somewhat
different distribution of the same elements in each." It is impossible
for the opportunist position to be more cogently stated. It is, indeed,
a strange paradox that political integrity should be traditionally
associated with the name of Gladstone, who accomplished more
than any other of our statesmen in changing statesmanship into
demagogy. His pronouncedly religious temperament, however, led to
extraordinary results, and his psychological condition was best
expressed in the well-known epigram that "he followed his
conscience in the same manner that the driver of a gig follows the
horse." It was not that he was deliberately insincere. He could
Welcome to our website – the ideal destination for book lovers and
knowledge seekers. With a mission to inspire endlessly, we offer a
vast collection of books, ranging from classic literary works to
specialized publications, self-development books, and children's
literature. Each book is a new journey of discovery, expanding
knowledge and enriching the soul of the reade

Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.

Let us accompany you on the journey of exploring knowledge and


personal growth!

ebookname.com

You might also like