12

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?

Muhd
  • 24,305
  • 22
  • 61
  • 78

2 Answers2

17

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

Daniel DiPaolo
  • 55,313
  • 14
  • 116
  • 115
  • 9
    This works beautifully, way better than the reflection in the other answer. I used `Gson gson = new GsonBuilder().serializeSpecialFloatingPointValues().serializeNulls().create(); System.out.println(gson.toJson(obj));` which let me see nulls, NaN and infinity values. – Muhd Apr 19 '11 at 21:23
  • This doesn't work quite well with mocked objects or static variables – hasanac Dec 05 '17 at 08:25
12

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

lobster1234
  • 7,679
  • 26
  • 30