Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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:

  • What's the simplest way to print a Java array?
  • Best pretty-printing library for Java?
  • Java dump an object
like image 847
gavenkoa Avatar asked Feb 07 '12 10:02

gavenkoa


People also ask

Can you print 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 when object is printed Java?

If you print any object, Java compiler internally invokes the toString() method on the object. So overriding the toString() method, returns the desired output, it can be the state of an object etc. depending on your implementation.


2 Answers

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.

like image 168
Joni Avatar answered Sep 21 '22 01:09

Joni


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.

like image 22
david99world Avatar answered Sep 21 '22 01:09

david99world