I'm looking for a library function (ideally from a commonly used framework e.g. Spring, Guava, Apache Commons etc.) that will nicely print the values of any Java object.
This is a general question rather than a specific one. Have seen similar questions on StackOverflow for which a common answer is "implement your own toString()
method on the class" but this option isn't always practical - am looking for a general way of doing this with any object I come across, which may originate from third party code. Another suggestion is to use RefectionToStringBuilder from Apache Commons, e.g:
new ReflectionToStringBuilder(complexObject, new RecursiveToStringStyle()).toString()
But this has limited use - e.g. when it comes across a collection it tends to output something like this:
java.util.ArrayList@fcc7ab1[size=1]
An actual use case example is to log an Iterable<PushResult>
returned from JGit's pushCommand.call()
method - if posting an answer please make sure it would work with this as well as any other complex object.
Prettyprint is the process of converting and presenting source code or other objects in a legible and attractive way. A prettyprinter takes blocks of code and prints them in an aesthetically pleasing fashion, presenting the characters with line breaks and indentations to make the code comprehensible.
The print(Object) method of PrintStream Class in Java is used to print the specified Object on the stream. This Object is taken as a parameter. Parameters: This method accepts a mandatory parameter object which is the Object to be printed in the Stream. Return Value: This method do not returns any value.
You could try and use Gson. it also serializes Arrays, Maps or whatever....
MyObject myObject = new MyObject();
Gson gson = new GsonBuilder().setPrettyPrinting().serializeNulls().create();
gson.toJson(myObject);
For deserialization use:
gson.fromJson(MyObject.class);
For typed maps see this answer: Gson: Is there an easier way to serialize a map
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With