Easy Way to Write toString() Method

It starts to get boring to write toString() method especially if you want to include a lot of instance variables. If you are using eclipse, you can generate toString() method code by clicking Source > Generate toString()…. Method looks ugly to be honest.


@Override
public String toString(){
   return"Message [id="+ id +", message="+ message +", created="
         + created +", author="+ author +", comments="+ comments
         +", links="+ links +"]";
}

Luckily, there is an open source library that takes care of it for you. Apache Commons Lang provides some methods that you might can use to write toString() method in cleaner way.

This all you have to write toString() method using Apache Commons.

public String toString() {
   return ToStringBuilder.reflectionToString(this);
}

Above method outputs all the variables with the memory location of a object that you are trying to print. We can remove memory location of a object by writing code like follows.

public String toString() {
   return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE);
}

There are other styles too if you want to explore on it. The dependency for Apache Commons is as follows.

<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 -->
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.5</version>
</dependency>

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s