How do I use Jakarta Commons ToStringBuilder?

Category: commons.lang, viewed: 8478 time(s).

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.

Click here to lend your support to: Kode Java Org and make a donation at www.pledgie.com !

 

Uncensored Newsgroups
Download Hundreds of Complimentary Industry Resources

Get hundreds of popular Industry magazines, white papers, webinars, podcasts, and more; all available at no cost to you. With more than 600 complimentary offers, you'll find plenty of titles to suit your professional interests and needs. Click Here and Sign up today!

Java Training

Sponsored Links

Our Friends

Statistics

Locations of visitors to this page
visitor stats