java - 当我们覆盖 toString() 方法时,我们应该始终返回对象的字符串表示形式吗?

标签 java overriding

实际上,toString 方法应该返回对象的字符串表示形式。

在一个项目中,我发现一些类重写了允许返回 null 的 toString 方法。

喜欢:

@Override
public String toString() {
    .......
    return null;
}

对我来说,这种做法违反了 toString 方法的主要提议,该方法应返回对象的 String 表示形式。

Object.toString() 的 API 文档说:

public String toString()

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.

当我们覆盖 Object 的 toString() 方法时,您不应该返回 null 吗?

最佳答案

toString 主要用于表示观众是程序员的东西,比如调试和日志记录,我们需要看到某个对象的一些文本版本。当您在日志文件或调试器中看到该对象时,请使用对您有用的信息。来自 Effective Java,第 3 章,第 10 项:

While it isn’t as important as obeying the equals and hashCode contracts (Item 8, Item 9), providing a good toString implementation makes your class much more pleasant to use. The toString method is automatically invoked when an object is passed to println, printf, the string concatenation operator, or assert, or printed by a debugger.

Object#toString 的 API 文档中的建议是:

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.

返回 null 永远不会算作提供信息,而且很容易产生误导。似乎有人在使用 toString 做一些它从未打算做的事情。

关于java - 当我们覆盖 toString() 方法时,我们应该始终返回对象的字符串表示形式吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32378264/

相关文章:

python - 在类上覆盖 dict()

javascript - Prestashop 1.6.1.16 - 我的 js 文件已加载,但没有看到我的函数

java - 创建新的 TextView 不起作用

java - 无法在 Eclipse 中编辑 Android Manifest 文件

java - 尝试检索 json 节点时出现 ClassCastException

java - 在 Java 中重写抽象静态方法?

objective-c - 如何用更具体的类型覆盖父类(super class)的属性?

java - 在 Java 的同一个接口(interface)中实现多个类?

无端口转发的 Java Web 通信

java - 并发队列 - 一般问题(描述和用法)