A Generic toString in Java

Alternative to Java’s toString() method: A generic toString in java

For the impatient readers who know the problem I am trying to solve and need the code can scroll down to the Source code section.

If you are still reading then, let us describe the problem in hand.

Problem Statement

Have you ever faced an issue where you included a POJO(Plain Old Java Object) in your source code and tried to print it’s state in the logs or may be on the console. But unlike your expectations you ended up with some ugly object references which gives no good representation of the data you require.

This thing gets worse when the POJO is a part of some sealed jar where we do not have any control over the toString() method of the POJO.

It becomes much more worse, if we have control over the POJO’s source code but eventually have some one in the team who keeps on changing the definition and does not change the toString() method.

Solution

I tried writing a generic solution where I am not forced to reach out to all my POJO’s and individually override them. I also wanted to get rid of frequent modifications of the POJO and missing out essential information while printing the state of the object.

Trade Offs

For getting this much of guarantee from the source code which relieves you of all the worries of subsequent modifications and inaccessibility to the source code, it definitely requires to employ Java’s Reflection. Hence, there is a slight performance overhead. But I believe in the world of 3+ GHz i5 and i7 processors and 8-16 gigs or RAM, this is acceptable.

Please read the class level comment to understand the options.

 

Note: The code above does not take into account the Enum types and the properties in the parent class (in case of an hierarchical object relationship. Below is another piece of the code enhanced enough to pick up enum types and fields from parent class which are not in the framework library.

For example: If we have a class hierarchy A extends B extends Date, then this utility prints the properties of A and B and the value of Date field if needed, but it doesn’t print all the properties of Date and GregorianCalendar and Object.

 

Stay connected and stay Subscribed