How do I use Apache Commons Lang ToStringBuilder class?

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 ToStringBuilderDemo {
    private Long id;
    private String firstName;
    private String lastName;

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

        System.out.println(demo);
    }

    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:

org.kodejava.example.commons.lang.ToStringBuilderDemo@d716361[
  id=1
  firstName=First Name
  lastName=Last Name
]

Below are example result of the other ToStringStyle:

  • ToStringStyle.DEFAULT_STYLE
org.kodejava.example.commons.lang.ToStringBuilderDemo@d716361[id=1,firstName=First Name,lastName=Last Name]
  • ToStringStyle.NO_FIELD_NAMES_STYLE
org.kodejava.example.commons.lang.ToStringBuilderDemo@d716361[1,First Name,Last Name]
  • ToStringStyle.SHORT_PREFIX_STYLE
ToStringBuilderDemo[id=1,firstName=First Name,lastName=Last Name]
  • ToStringStyle.SIMPLE_STYLE
1,First Name,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

<!-- http://repo1.maven.org/maven2/commons-lang/commons-lang/2.6/commons-lang-2.6.jar -->
<dependency>
    <groupId>commons-lang</groupId>
    <artifactId>commons-lang</artifactId>
    <version>2.6</version>
</dependency>

Wayan Saryada

Programmer, runner, recreational diver, currently living in the island of Bali, Indonesia. Mostly programming in Java, creating web based application with Spring Framework, Hibernate / JPA.

Leave a Reply