Generate Java Object from toString representation [duplicate]

匿名 (未验证) 提交于 2019-12-03 02:03:01

问题:

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

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



回答2:

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



回答3:

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.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!