实际上,toString方法应返回对象的String表示形式.
在一个项目中,我发现一些类重写了toString方法,从而允许返回null.
喜欢:
@Override
public String toString() {
.......
return null;
}
对我来说,这种做法违反了toString方法的主要建议,后者应返回对象的String表示形式.
API文档的Object.toString()说:
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.
API文档中有关Object#toString的建议是:
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来完成原本不希望的事情.