ToStringHelper(guava) – SimpleResponse

I came across a handy Java class that is from Google Commons named ToStringHelper. This is where I found the usage of ToStringHelper by reading openscoring source code.

Villu was wrote this tiny SimpleResponse class in openscoring.common which is serializable and only one attribute, three methods, the getter, setter and the toString method, which is implemented using the MoreObjects.toStringHelper class.

First, we need to cover something basic about “toString“.  It is a method that comes with class Object, basically means every class in Java is kind of a object and it should always inherit this default toString method unless overwritten. However, who need a hashcode, right?!. User tend to need something that is more informative and concise, like you might want the first name and last name out of a person object? a title, author in the textual format of a book class so on and so forth. You can overwrite toString in whatever way you prefer, but using the toStringHelper really made this part easy and consistent.

toStringHelper

using tostringhelper

toStringHelper_default

default tostring

Keep this little trick in your toolbox and hopefully it is helpful sometime.

 

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