This question already has an answer here:
We all know how to implement toString() method. It could be slightly custom implementation and different pattern how we print the object data.
Using the generated toString, can we recreate the Object? I am not talking about Serialization
here.
Let me explain a scenario, You might have an application running happily in production and your log prints these objects when you received some request and doing some operations. And some issue might have raised.
To replicate certain hard bugs, you will go back to your unit test cases/mockito to recreate the problem with similar data.
Now If I can reproduce the object from it's toString representation, since all of it's dependency objects also implements toString, I will be able to clear most of these scenarios.
Is there any by default plugin/tool to do the same? If not, It could be my next try-on project :)
The toString() method was designed to return a readable representation of an object, not a full representation.
If you want to marshal your object into a string that can later be unmarshalled, the usual options are XML, JSON, flat file,... Check out JAXB perhaps.
You could opt for a custom format, the only requirement being that all the information you need to reconstruct the object is in there and you write a custom parser to build the object again. If said custom format also happens to be readable, you can plug it into toString().
No, there is no general way
(Consider the case of a toString method that returns the empty string)
Your best bet is to log more details in the case of an Exception, possibly on a finer log level
No you cannot.
toString()
is only intended for logging
and debug
purposes. It is not intended for serializing the state of an Object
.
If the object in question supports serialization
then go with serialization and deserialization
to find out how to do this.
来源:https://stackoverflow.com/questions/25927052/generate-java-object-from-tostring-representation