java examples
Home Java Examples Resources Java Interview Questions
Brainpower SEO

How to use Jakarta Commons ToStringBuilder?

The toString() method defined in the java.lang.Object can be overriden 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 Commons Lang library offers a good utility for creating this toString() information. Here I give a simple example using the ToStringBuilder class.

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 String toString()
    {
        return new ToStringBuilder(this,
                ToStringStyle.MULTI_LINE_STYLE)
                .append("id", id)
                .append("firstName", firstName)
                .append("lastName", lastName)
                .toString();
    }
 
    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 = " + example);
    }
}

The result of the code above is:

example = ToStringBuilderExample@addbf1[
  id=1
  firstName=First Name
  lastName=Last Name
]

If you want to make the code event more simple, use the line below.

ToStringBuilder.reflectionToString(this);

Using this line the ToStringBuilder will the hard job of finding information of our class and return the string information.