Easy Way to Write toString() Method

Posted by coffeetechgaff on April 10, 2017

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.

                      
                      
                          org.apache.commons
                          commons-lang3
                          3.5