Generating Java Getter and Setters with Regular Expressions and IntelliJ IDEA

This is mostly a story about the power of a good UI, again demonstrated by IntelliJ IDEA (Version 9, Ultimate).

I have a buddy that says, “If you have a problem, and you want to solve it with regular expressions, then you have two problems.”

I’ve done a fair bit of regular expressions in my day.  My first contracting gig way back in 1991 (I was 24) was using regex to transform specifications in Word documents into something parseable by a system that would store the data in a database that could then be searched by a desktop app.  I’ve never been an expert at regex, at least not since I left that gig, but with a cheatsheet I know what I am doing, mostly.  Still, it often takes me more time than it’s worth.  Enter IntelliJ IDEA.

I had a generated interface for what amounts to an Entity with hundreds of getters (or the interfaces of them).  I needed to create a value object from it.  Of course, I’ll eventually use code generation, but I’m need to move quickly right now, so I figured I’d take a stab at using RegEx.  I started using IDEA and was surprised to see that as I typed my RegEx, it caught many of my mistakes by showing red underlines (like Word misspelling) and gray backgrounds for warnings.  Within 5 minutes, I had it working.  That would have taken me 20 minutes easily with a decent likelihood of being a complete waste of time if I couldn’t figure out my mistakes through eyeball inspection.

Here’s the search that matches “Type getFoo();” or “boolean isFoo();” (with support for generics):

([ \t]+)([a-zA-Z.0-9<>]+)[ ]+(get|is)([^(]*)\(\);

And the replacement expression to make:
Type Foo;
Foo getFoo(return Foo;):
void setFoo(Foo Foo) {this.Foo=Foo);

\t$2 $4;\n\tpublic $2 $3$4(){return $4;}\n\tpublic void set$4($2 $4){this.$4 = $4;}



Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: