Monday, February 06, 2006

Simple toString() Hack

When you want something short, and you're not in the mood for reflection:
  public String toString() {
    return MyClass.class.getSimpleName()
        + new LinkedHashMap<String, Object>() {{
      put("foo", foo);
      put("bar", bar);
      put("tee", tee);
    }};
  }
Results in:
  MyClass[foo: fooValue, bar: barValue, tee: teeValue]
I use LinkedHashMap because it maintains the order.

7 Comments:

Blogger Eugene Kuleshov said...

Look cool, but it creates anonymous inner class. Would be neat if compiler could detect such stuff and inline it as plain string concatenation. From other hand commons ToStringBuilder does about that... :-)

Also, what about types? I can't believe you've used non-typesafe collection. ;-)

5:06 PM  
Blogger Anjan said...

Hi Bob,

yeah, Cool -- I've been occassionally (found it initially from the Java specialists newsletter) using this technique of creating inline maps for junit tests.

I can't use it in production apps because of the number of classes it creates.

BR,
~A

5:41 PM  
Blogger Bob said...

Ha ha, Eugene. The types were actually there, but I forgot to escape the '<'.

5:59 PM  
Blogger Bob said...

Also, I don't think the number of classes is worth worrying about.

6:00 PM  
Blogger Bob said...

You don't have to keep the square brackets and commas straight.

8:53 AM  
Blogger Eugene Kuleshov said...

Bob, number of clsses is not an issue untill you hit into MaxPermSize limit. JVM default is not that big and it usually require tweaking for large app. Those inner classes make this even worse.

And since when Object is consideted a strong type? :-)

9:44 AM  
Blogger Bob said...

You can increase the MaxPermSize limit as you said. I've seen excessive String interning max it out, but not classes. That would be a *lot* of classes.

12:13 PM  

Post a Comment

<< Home