Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to log internals of an arbitrary object in Java?

Tags:

java

I have a Java object with some unknown structure. Now I want to output this structure (properties and their values) to log file. And of course I'm interested to do this in recursive mode. Are there any libraries that can help me?

like image 555
yegor256 Avatar asked Jul 15 '11 18:07

yegor256


2 Answers

XStream is extremely good at printing object graphs, even handling cycles without any extra configuration or extra code in your classes (i.e. no messing with toString()'s). Just add the library and you can do this to anything and get nice, useful output:

log.debug("The object: {}", new XStream().toXML(anyObject));

That will give you XML output. If you prefer JSON, you can get it with a tiny bit more work as detailed in the XStream JSON tutorial.

like image 58
Ryan Stewart Avatar answered Oct 12 '22 00:10

Ryan Stewart


I suggest you look either at Apache Commons BeanUtils or Apache Commons Lang, specifically ReflectionToStringBuilder.

like image 25
Olaf Avatar answered Oct 11 '22 23:10

Olaf