Generate Java Object from toString representation [duplicate]

醉酒当歌 提交于 2019-11-29 17:44:35

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.

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