Monday, October 24, 2016

Printing an object's properties for debug purposes

Quite often, we override the 'toString()' method of an object to print its properties. But there are a number of reusable utilities that can be used for the same.

In Java, the popular Apache Commons Lang3 package contains a class called ReflectionToStringBuilder  that has static overloaded methods 'ToString()' to print all fields using reflection. You can also specify a few formatting options and the fields to exclude.

Another option is Java, is to use the JSON libraries to print the object as a json string. The Google librarly Gson can be used to print (or pretty print) an object as a json string.

In .NET, you can either use the ObjectDumper library or you can use the object json formatter - newtonsoft JSON library

No comments:

Post a Comment