Wednesday, March 19, 2014

Override toString() method with ToStringBuilder

One fancy way of toString method implementation is in using of ToStringBuilder class.
With this class you don't need to specify all the objects for output and you get a flexible mechanism of building and formatting your object's string representaion.
Just a couple of strings:

<dependency>
    <groupId>commons-lang</groupId>
    <artifactId>commons-lang</artifactId>
    <version>2.5</version>
</dependency>

import org.apache.commons.lang.builder.ToStringBuilder;

@Override
public String toString() {
return ToStringBuilder.reflectionToString(this);
}

Got it!

See more information on official reference documntation: http://commons.apache.org/proper/commons-lang/javadocs/api-3.1/org/apache/commons/lang3/builder/ToStringBuilder.html

Another very good article about ToStringBuilder by Lokesh Gupta (with nice samples)
http://howtodoinjava.com/2013/06/03/how-to-override-tostring-effectively-with-tostringbuilder/