2

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 :)

RaceBase
  • 18,428
  • 47
  • 141
  • 202
  • There is *no* general way to do this. That is, "toString" is *not* like a "toRepr" as found in some languages. If *custom* objects implement "toString" such that it implements "serialization" semantics, then it should be equally as trivial to recreate *custom* objects from such, assuming that such a mapping can be performed (that is, the relevant data was "serialized" in the string). – user2864740 Sep 19 '14 at 05:37
  • Since this question is marked duplicate I've posted an answer on the original question [here](http://stackoverflow.com/questions/2596230/converting-back-from-tostring-to-object/25928621#25928621) – Rajeev Sreedharan Sep 19 '14 at 07:31

3 Answers3

1

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().

nablex
  • 4,635
  • 4
  • 36
  • 51
0

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

folkol
  • 4,752
  • 22
  • 25
0

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.

Ankur Singhal
  • 26,012
  • 16
  • 82
  • 116