Looking for standard library or technique to get pretty-printed representation of OBJECT for Java
Asked Answered
P

2

6

In order to understand internals of some code or print dumps on errors I use pp-like functions in Python and Emacs lisp.

Now I come to to Java and look for standard library or tecnique to get pretty-printed representation of OBJECT for Java.

Seems that current Java specification allow introspection of Java object at runtime. But introspection may be not so powerful. m(Object o) can not be called with new Object [] arg?

NOTE I am NOT looking to source code beautifier! I am looking for runtime pretty print Java object dumping.

NOTE2 These questions similar but not exactly same:

Paramedic answered 7/2, 2012 at 10:3 Comment(6)
That is a typical approach for languages as lisp and python. One sees it less for a compiled language like java. There it is setting a breakpoint and inspecting the variables in the debugger. That is not as intelligent, but you might consider altering your way of working. Implementing nice toStrings helps too.Congregational
@JoopEggen Thanks for tips about debuger! Do I need use some GUI debuger or jdb can nicely print class content (array of integer)? I use Emacs so it is easy store and process jdb output for me...Paramedic
To print class contend under jdb debugger use dump command!Paramedic
Answered by @gavenkoa. But though I can understand the clearity of Emacs, I would give an IDE a chance; there are other advantages too. NetBeans might be more simple than eclipse.Congregational
@JoopEggen I have many limitations on debug session: debugging apps without sources, deployed remotely and I want to have full debug log... I don't know how to make this in NetBeans...Paramedic
Remote debugging should be possible, but without sources? I think jdb then offers best screen estate.Congregational
J
12

You could use the ReflectionToStringBuilder from the Apache Commons Lang library.

Sample:

String dump = ReflectionToStringBuilder.toString(object);

As to your question:

m(Object o) can not be called with new Object [] arg?

Sure it can, arrays of Object is a subtype of Object.

Jahn answered 7/2, 2012 at 10:33 Comment(0)
R
7

For a quick and dirty solution to show the output of a Java object, you could use Jackson http://jackson.codehaus.org/ this will output the object in JSON.

Reeducate answered 7/2, 2012 at 10:32 Comment(1)
For anyone needing further details this can be done using ObjectMapper: (new com.fasterxml.jackson.databind.ObjectMapper()).writerWithDefaultPrettyPrinter().writeValueAsString(object);Pulpwood

© 2022 - 2024 — McMap. All rights reserved.