How do I use Apache Commons ToStringBuilder?

The toString() method defined in the java.lang.Object can be overridden when we want to give a more meaningful information about our object. We can simply return any information of the object in the toString() method, for instance the value of object’s states or fields.

The Apache Commons Lang library offers a good utility for creating this toString() information. Here I give a simple example using the ToStringBuilder class.

package org.kodejava.example.commons.lang;

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

public class ToStringBuilderExample {
    private String id;
    private String firstName;
    private String lastName;

    public ToStringBuilderExample() {
    }

    public static void main(String[] args) {
        ToStringBuilderExample example = new ToStringBuilderExample();
        example.id = "1";
        example.firstName = "First Name";
        example.lastName = "Last Name";

        System.out.println(example);
    }

    public String toString() {
        return new ToStringBuilder(this,
                ToStringStyle.MULTI_LINE_STYLE)
                .append("id", id)
                .append("firstName", firstName)
                .append("lastName", lastName)
                .toString();
    }
}

The ToStringStyle class allows us to choose the styling for our toString() method when we print it out. Here are the available styles that we can use.

  • ToStringStyle.DEFAULT_STYLE
  • ToStringStyle.MULTI_LINE_STYLE
  • ToStringStyle.NO_FIELD_NAMES_STYLE
  • ToStringStyle.SHORT_PREFIX_STYLE
  • ToStringStyle.SIMPLE_STYLE

The result of the code above is:

[email protected][
  id=1
  firstName=First Name
  lastName=Last Name
]

If you want to make the code event more simple by using the ToStringBuilder.reflectionToString() method to generate the string for the toString() method to return. Using this method the ToStringBuilder will the hard job of finding information about our class and return the string information.

Maven Dependencies:

<dependencies>
    <dependency>
        <groupId>commons-lang</groupId>
        <artifactId>commons-lang</artifactId>
        <version>2.6</version>
    </dependency>
</dependencies>