Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: How to convert any Object to a String representation of the data

Tags:

java

I'm trying to write some code that will take any object and convert it into a String representation of that object. Serialization will not include any transient properties and toString() is typically a memory address for the object. I can't expect the object to have a meaningful toString() defined or implement Serializable.

Is there any way to determine the data in an object and convert it to a String? I would be willing to write something to traverse through the class and use reflection to find data, if need be, but I was hoping to find something a little simpler.

Any suggestions would be appreciated. Thanks.

like image 813
Chad Cook Avatar asked Jun 04 '10 17:06

Chad Cook


2 Answers

Grab apache's commonns-lang. It has a ReflectionToStringBuilder that will do the reflection to stringing for you.

It also accepts Styles to allow you to customize the output.

like image 95
taer Avatar answered Sep 19 '22 10:09

taer


XStream is another option for producing XML from your objects.

like image 42
Dolph Avatar answered Sep 23 '22 10:09

Dolph