Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Printing out an object for debugging

I would like an easy way to print out a java object, or to say it another way, serialize an object as a string. I would like to see the values of all variables contained within the object, and if there are more objects (like a list or whatever) it should print out the stuff in that object as well. Basically, it would be something like JSON encoding, but JSON doesn't support infinity, and I need to see if there is infinity or NaN in one of the double or float values.

How can I do this?

like image 362
Muhd Avatar asked Apr 14 '11 20:04

Muhd


People also ask

Can you print out an object in Java?

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.

What happens if we print an object in Java?

Example 1: Java program to print the object When we print the object, we can see that the output looks different. This is because while printing the object, the toString() method of the object class is called. It formats the object in the default format.

Which method gets called when you print an object?

println() method to print object, it calls the toString() method of Object class.


2 Answers

You could use Gson to serialize to JSON as it now supports NaN and +/- infinity

like image 105
Daniel DiPaolo Avatar answered Oct 06 '22 22:10

Daniel DiPaolo


More often than not ToStringBuilder.reflectionToString(Object) works great. It wont work when doing Maps though.

like image 11
lobster1234 Avatar answered Oct 06 '22 22:10

lobster1234