Sunday Apr 20

Key Concepts

ToStringBuilder Style

PDFPrintE-mail
Friday, 01 April 2011 12:37
AddThis Social Bookmark Button

Apache Commons ToStringBuilder styles

I have found the humble Java toString() to be one of the most useful and powerful techniques in debugging and troubleshooting Java applications. That is only true, unfortunately, when and if the developers on the team override the Object.toString() method to provide useful details. One of the disciplines i try to have while developing Java code is always overriding the default toString, equals, and hashCode methods.

An effective way to implement the toString method is using the Apache Commons library toStringBuilder class. According to your needs the library propose five styles. I propose you in this article to take a look at the different styles.

Assists in implementing Object.toString() methods. This java class enables a good and consistent toString() to be built for any class or object.

ToStringBuilder class aims to simplify the process by:

  • allowing field names 
  • handling all types consistently 
  • handling nulls consistently 
  • outputting arrays and multi-dimensional arrays 
  • enabling the detail level to be controlled for Objects and Collections 
  • handling class hierarchies

 Let's take the following class and apply different to string style using ToStringBuilder :

Object to String example

public class Person implements Comparable {
    private long id;
    private String firstName;
    private String lastName;
        ....
    public String toString(){
         return new ToStringBuilder(this,ToStringStyle.SIMPLE_STYLE)
             .appendSuper (super.toString())
             .append      ("first name", firstName)
             .append      ("last name", lastName)
             .toString();
    }
}

Styles availables

StylesDescription
DEFAULT_STYLE The default toString style.
MULTI_LINE_STYLE The multi line toString style.
NO_FIELD_NAMES_STYLE The no field names toString style.
SHORT_PREFIX_STYLE The short prefix toString style.
SIMPLE_STYLE The simple toString style.;

Styles Output samples

 

Default style
ch.javatutorial.Person@4310b053[first name=John,last name=Smith]
Multi-line style
ch.javatutorial.Person@7b11a3ac[
  first name=John
  last name=Smith
]
No Field name style
ch.javatutorial.Person@7b11a3ac[John,Smith]
Short prefix style
Person[first name=John,last name=Smith]
Simple style
ch.javatutorial.Person@4310b053,John,Smith

Conclusion

The ToStringBuilder class is just one of many useful utility classes provided by the commons-lang library and the commons-lang library is just one of the useful libraries provided by the Apache Commons project.

Other related Java tutorial articles

 

 

Tags: java, default, style, tostring, styles, tostringbuilder, field, class, handling, library

Add comment


Security code
Refresh

Java Tutorial on Facebook