gpt4 book ai didi

java - 多个 toString 方法?

转载 作者:行者123 更新时间:2023-12-03 18:19:55 24 4
gpt4 key购买 nike

我在从对象列表生成逗号分隔的字符串时遇到了问题。此链接中解释了该问题 Convert string in list objects to comma separated

我已经使用 toString 方法解决了这个问题。以前我使用 toString() 方法作为字符串生成器来进行调试。因为我用它来生成逗号分隔值,所以我无法像以前那样调试它。

有没有什么方法可以同时做到这两者?

最佳答案

应该有一个单独的对象来处理格式化。这就是为什么您会在 java.text 中看到日期和数字的格式化对象,因为有这么多不同的格式,您需要与数据对象分开的专用格式化程序。

查看 toString 的用途,description given in the javadoc

Returns a string representation of the object. In general, the toString method returns a string that "textually represents" this object. The result should be a concise but informative representation that is easy for a person to read. It is recommended that all subclasses override this method.

Odersky/Spoon/Venners 的书 Programming in Scala 说:

The result of toString is primarily intended to help programmers by providing information that can be used in debug print statements, log messages, test failure reports, and interpreter and debugger output.

还有 Effective Java(第 10 条:始终覆盖 toString)似乎假定 toString 的目的是在调试或记录时向开发人员提供诊断信息。

我会保留用于调试的 toString 实现,并创建一个单独的 CSV 格式对象来处理 csv 生成。这样 toString 的目的仍然是调试,在对象作为数据持有者的工作和 CSV 生成之间保持关注点分离。

关于java - 多个 toString 方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18768865/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com