笔记
The general contract for toString says that the returned string 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方法。. It consists of the class name followed by an “at” sign (@) and the unsigned hexadecimal representation of the hash code, for example, PhoneNumber@163b91.While it isn’t as critical as obeying the equals and hashCode contracts (Items 10 and 11), providing a good toString implementation makes your class much more pleasant to use and makes systems using the class easier to debug.
不强制要求,属于锦上添花的事情。When practical, the toString method should return all of the interesting information contained in the object。
方便调试和记录日志。如果只包含部分字段,在这些字段内容相同的时候,容易造成混淆,不能区分具体的对象。to specify the format of the return value in the documentation. It is recommended that you do this for value classes。 If you specify the format, it’s usually a good idea to provide a matching static factory or constructor so programmers can easily translate back and forth between the object and its string representation.
对于值类,可以声明toString返回值的格式。如果要解析返回值,最好是由类的发布者提供工具方法。后面有变动,可以同步修改实现。不至于造成用户不能感知到的变更。Whether or not you specify the format, provide programmatic access to the information contained in the value returned by toString.
一定要为toString中包含的信息提供访问方法,不要去解析toString返回的内容。这个内容不稳定,不可信赖,容易引入bug。You should, however, write a toString method in any abstract class whose sub·classes share a common string representation.
可以在抽象类中实现toString方法,条件是子类共享相同的表示形式。Google’s open source AutoValue facility, discussed in Item 10, will generate a toString method for you, as will most IDEs.
偷懒工具。To recap, override Object’s toString implementation in every instantiable class you write, unless a superclass has already done so.
理解与思考
- 覆写toString方法,返回可读性高的内容,主要是为了方便调试和记录日志。
- 不要试图去解析toString方法的返回值。如果要解析,也最好由类提供方给出解析方法,方便扩展。
- toString的输出内容要覆盖equals方法里用到的字段,否则容易丢掉信息,不利于定位。