Object content pretty print

I had an experience working on a project with a very large team (200+ developers). The team was divided into tiers. There were Portal tier, Enterprise Service tier, and Data Tier. With this kind of team structure, a simple web page loading would invoke software written by all three teams. When things went wrong, it was very difficult to chase down the problem. For that reason, I created a software to print the content of Java objects at run time for logging purpose. I used Java reflection to implement it. Since then, I used it from project to project. It was pretty useful for debugging purpose. Few years after that, I found Apache had created an API for the same functionality.

This blog provides an example of pretty printing of Java object using the Apache common ReflectionToStringBuilder. ReflectionToStringBuilder uses the same method, Java reflection, that I used to print Java object content. The usage is pretty straightforward. All you need to do is to override the toString() method of the classes that you would like to have the pretty print capability with the following,

public String toString() {
           return ReflectionToStringBuilder.toString(this, StandardToStringStyle.MULTI_LINE_STYLE);
}

In order to provide an example, I created three simple classes to show the usage.

prettyprint

Once the toString() methods are overridden, we could use the following code to test it.

package util;

import org.apache.commons.lang3.builder.ReflectionToStringBuilder;

import vo.Person;
import vo.PersonAddress;
import vo.PersonName;

public class Test {

public static void main(String[] args) {

// build test data
Person p = new Person();
PersonAddress pa = new PersonAddress();
pa.setAddressLine1(“5700 Bou Ave “);
pa.setCity(“Rockville”);
pa.setState(“MD”);
pa.setZip(“20852”);

PersonName pn = new PersonName();
pn.setFirstName(“John”);
pn.setLastName(“Doe”);

p.setPersonAddress(pa);
p.setPersonName(pn);

// test the pretty print
System.out.println(ReflectionToStringBuilder.toString(p));

}

}

The expected outcome is here,

vo.Person@5bc85bc8[personName=vo.PersonName@60106010[
FirstName=John
LastName=Doe
MiddleName=<null>
],personAddress=vo.PersonAddress@5e045e04[
addressLine1=5700 Bou Ave
addressLine2=<null>
city=Rockville
state=MD
zip=20852
]]

This is simple and useful for pretty much every projects.

To download the complete example, here are the files.

Leave a comment

Design a site like this with WordPress.com
Get started