从toString表示形式生成Java对象 [英] Generate Java Object from toString representation

查看:111
本文介绍了从toString表示形式生成Java对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们都知道如何实现 toString ()方法.可能是稍微自定义的实现,以及我们如何打印对象数据的不同模式.

We all know how to implement toString() method. It could be slightly custom implementation and different pattern how we print the object data.

使用生成的 toString ,我们可以重新创建对象吗?我不是在这里谈论 Serialization .

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.

现在,如果我可以从它的toString表示形式复制对象,由于所有依赖项对象还实现了toString,因此我将能够清除大多数情况.

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

推荐答案

toString()方法旨在返回对象的可读表示形式,而不是完整表示形式.

The toString() method was designed to return a readable representation of an object, not a full representation.

如果您想将对象编组为一个字符串,以后可以将其解组,则通常的选项是XML,JSON,平面文件,...也许可以查看JAXB.

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.

您可以选择自定义格式,唯一的要求是重构对象所需的所有信息都在其中,然后编写自定义解析器以再次构建对象.如果上述自定义格式也可以读取,则可以将其插入toString().

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

这篇关于从toString表示形式生成Java对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆