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:
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. ;-)
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
Ha ha, Eugene. The types were actually there, but I forgot to escape the '<'.
Also, I don't think the number of classes is worth worrying about.
You don't have to keep the square brackets and commas straight.
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? :-)
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.
Post a Comment
<< Home