Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Write toString() once and for all?

Tags:

java

tostring

I want to have all of my classes implement toString() the same way using Java reflection. There are two ways I came up with.

  1. Create a base class such as MyObject overriding toString() and all my classes would extend it, but I'm not sure if it'd be an overkill.

  2. Use Eclipse to generate the overridden toString() for each class. The downside of it is that there'd be a lot of code redundancy.

Which is the preferred method? If you go with Eclipse templates, is there a way to auto-generate it when you do New > Class, instead of having to do Source > Generate toString() every time?

like image 536
Tom Tucker Avatar asked Oct 17 '11 23:10

Tom Tucker


2 Answers

As Harkness says, use commons-lang ReflectionToStringBuilder.

Rather than have a base class, I'd use AOP such as aspectj to inject this implementation into all of your classes at compile time.

Another option is to use a tool like ASM to transform your classes at compile time to inject toString methods. Both approaches use the same basic concepts, ASM being a more 'raw' version of class file modification.

like image 101
MeBigFatGuy Avatar answered Sep 20 '22 01:09

MeBigFatGuy


See ToStringBuilder and its subclass ReflectionToStringBuilder from Apache Commons Lang. The latter would allow you to implement toString() generically in your base class or add it to the template:

public String toString() {
    return ReflectionToStringBuilder.toString(this);
}
like image 40
David Harkness Avatar answered Sep 20 '22 01:09

David Harkness