筆記
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.
不強(qiáng)制要求,屬于錦上添花的事情。When practical, the toString method should return all of the interesting information contained in the object。
方便調(diào)試和記錄日志。如果只包含部分字段,在這些字段內(nèi)容相同的時(shí)候,容易造成混淆,不能區(qū)分具體的對(duì)象。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.
對(duì)于值類(lèi),可以聲明toString返回值的格式。如果要解析返回值,最好是由類(lèi)的發(fā)布者提供工具方法。后面有變動(dòng),可以同步修改實(shí)現(xiàn)。不至于造成用戶不能感知到的變更。Whether or not you specify the format, provide programmatic access to the information contained in the value returned by toString.
一定要為toString中包含的信息提供訪問(wèn)方法,不要去解析toString返回的內(nèi)容。這個(gè)內(nèi)容不穩(wěn)定,不可信賴,容易引入bug。You should, however, write a toString method in any abstract class whose sub·classes share a common string representation.
可以在抽象類(lèi)中實(shí)現(xiàn)toString方法,條件是子類(lèi)共享相同的表示形式。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.
理解與思考
- 覆寫(xiě)toString方法,返回可讀性高的內(nèi)容,主要是為了方便調(diào)試和記錄日志。
- 不要試圖去解析toString方法的返回值。如果要解析,也最好由類(lèi)提供方給出解析方法,方便擴(kuò)展。
- toString的輸出內(nèi)容要覆蓋equals方法里用到的字段,否則容易丟掉信息,不利于定位。