Talking about my stuff

July 21, 2010

Groovy solution to the static class name problem

Filed under: Uncategorized — agoodspeed @ 9:23 pm

If you have ever done logging where you want to establish the logger based on the class name, you have probably ended up doing something dodgy, like coding a String into each class essentially documenting the class name. This works until you mistype it, or worse, forget to change it from wherever you copied it from.

The Java solution usually looks like:

private static final String className = "foo.Bar";
private static Logger log = Logger.getLogger(className);

Groovy lets you reference “this” within a static context and returns the Class object for it. It seems like that would solve this problem, and it does, but you have to be careful.

At least in my version of Groovy (still at 1.5.6 I’m afraid) the parser is not smart enough to resolve something like:

private static final String className = this.name

Here it backs off of the Groovy static use of “this” and complains about name being a missing property. Using a method invocation – getName() – is somewhat better. It will work in place of the above, but if you try to reference either from within a static method (like main) the compile will fail with something like:

<code>Non-static variable ‘this’ cannot be referenced from the static method main.</code>

So to use this effectively in a static context it is useful to put it into something with a name that is not a reserved word. Here is a solution that works for me.

private static final Class thisClass = this
private static final String thisClassName = thisClass.name
private static Logger log = Logger.getLogger(thisClassName)

I hope this helps someone with similar desires.

Advertisement

Leave a Comment »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Connecting to %s

Theme: Rubric. Blog at WordPress.com.

Follow

Get every new post delivered to your Inbox.