8

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.

1
  • It's not clear if you want an informational representation (for display, debugging) or a textual serialization (so that the object can be restored from the string). Commented Jun 4, 2010 at 18:28

4 Answers 4

11

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.

Sign up to request clarification or add additional context in comments.

Comments

5

XStream is another option for producing XML from your objects.

Comments

3

XMLEncoder might be suitable. It serializes the object to XML, which is human-readable.

Comments

2

The java reflection api is a pretty powerful way to peer into the object, you can use it to write some custom converter to extract the info into your favorite format.

You can also use java's Marshaller api to convert it to straight up xml. http://java.sun.com/javase/6/docs/api/javax/xml/bind/Marshaller.html

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.