Gaurav
Gaurav

Reputation: 1567

Alternative for toString() in java

What I have is an unmarshalled java object from XML. The parts of this unmarshalled object is sent to various class for processing. I need to log the contents of the unmarshalled object. I can easily override the toString() method but the problem is that in this case the classes are generated at build time using xjc and I cannot override the toString() in those classes as they will be removed when generated again.

I am looking for some other alternative to print the contents. Any Idea ?

Upvotes: 0

Views: 4528

Answers (4)

Satya Jasti
Satya Jasti

Reputation: 49

Write a helper class which takes the unmarshalled Java Object and gives you its string representation using reflection, if you don want to use reflection since you know your xsd and unmarshalled contents you can hard code them.

Upvotes: 0

Stephen C
Stephen C

Reputation: 718936

Don't use toString() for marshalling. That's not what it is intended for. (Refer to the javadocs for java.lang.Object for a guide to what that method is intended for.)

Even if you do decide to implement marshalling / unmarshalling by hand, you should not attempt to use toString() for this purpose.

Upvotes: 1

bmargulies
bmargulies

Reputation: 100051

You could use an xjc plugin to generate the toString you want.

Upvotes: 2

craigforster
craigforster

Reputation: 2669

You could write a utility class that uses reflection to inspect the object and either return a string representation of it (in whatever format you need) or have it log the string representation directly.

Upvotes: 0

Related Questions