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(); = "1";
        example.firstName = "First Name";
        example.lastName = "Last Name";


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

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.SIMPLE_STYLE

The result of the code above is:

  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

<!-- -->