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 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.commons.lang;

import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.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.JSON_STYLE
  • ToStringStyle.MULTI_LINE_STYLE
  • ToStringStyle.NO_CLASS_NAME_STYLE
  • ToStringStyle.NO_FIELD_NAMES_STYLE
  • ToStringStyle.SHORT_PREFIX_STYLE
  • ToStringStyle.SIMPLE_STYLE

The result of the code above is:

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

Below are example results of the other ToStringStyle:

  • ToStringStyle.DEFAULT_STYLE
org.kodejava.commons.lang.ToStringBuilderDemo@d716361[id=1,firstName=First Name,lastName=Last Name]
  • ToStringStyle.JSON_STYLE
{"id":1,"firstName":"First Name","lastName":"Last Name"}
  • ToStringStyle.NO_CLASS_NAME_STYLE
[id=1,firstName=First Name,lastName=Last Name]
  • ToStringStyle.NO_FIELD_NAMES_STYLE
org.kodejava.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

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.14.0</version>
</dependency>

Maven Central

Wayan

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.