java - 多个 toString 方法?

标签 java overriding

我在从对象列表生成逗号分隔的字符串时遇到了问题。 此链接中解释了该问题 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/

相关文章:

java - 如何在控制台启动时设置数据库连接参数 jar spring-boot app

overriding - 使用 Bloomberg API 进行多次覆盖

Android 覆盖显式 Intent

c# - 如何改进 C# 中方法重载的枚举标识结构

java - 正确覆盖 equals 方法

Java 系统依赖图 API

java - Spark Java语言加载数据集的最佳方式

Java:不可变类的伪setter方法

c++ - 使用覆盖 new[] 运算符创建字符串数组

java - 调用 Controller 方法时出现 InspirationTargetException - JavaFX