toString() using Apache Utility

In my first post, I provided the toString() implementation using Java Reflection. But one main drawback is we should implement the same implementation for all the super classes, otherwise super class fields won’t be printed. So this is an overburden

We do not need to create our own implementation each and every time as Apache is providing a utility class to do this task.

The Util class is ReflectionToStringBuilder from the common-lang.jar. So we should use the toString() method available in the ReflectionToStringBuilder class.

Please refer the below example,

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

public class Model {

    private String field1;

    public String toString() {
        return ReflectionToStringBuilder.toString(this);

But by default the static and transient fields won’t be printed. So use the appropriate method from the ReflectionToStringBuilder. i.e) Use toString(Object object, ToStringStyle style, boolean outputTransients, boolean outputStatics)

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s