ToStringBuilder Style
|
|
|
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 :
Styles availables
| Styles | Description |
|---|---|
| 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 |
|
| Multi-line style |
|
| No Field name style |
|
| Short prefix style |
|
| Simple style |
|
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 , tostringbuilder , field , class , handling , library , commons