java.lang.Object提供toString方法。一般它包含类型+@+无符号的十六进制的hashcode值。例如“PhoneNumber@163b91.”
提供一个toString方法将会使类更便于使用。toString方法将会在println,printf,assert调用的时候自动调用。如果提供一个好的toString方法给PhoneNumber,可以很容易的提供诊断消息:
System.out.println("Failed to connect: " + phoneNumber);
在实践中,toString方法应该返回对象包含的所有感兴趣信息。
在实现toString方法的时候需要决定是否需要指定返回值的格式。在值对象类中,是需要指定的。
指定格式的好处是它将对象变成一个标准的,清楚的,可读的对象。缺点是toString将会返回你指定的格式。而你将不能修改它。
是否需要指定格式,需要清楚的文档化你的意图。例如:
1
/** *//**
2
* Returns the string representation of this phone number.
3
* The string consists of fourteen characters whose format
4
* is "(XXX) YYY-ZZZZ", where XXX is the area code, YYY is
5
* the prefix, and ZZZZ is the line number. (Each of the
6
* capital letters represents a single decimal digit.)
7
*
8
* If any of the three parts of this phone number is too small
9
* to fill up its field, the field is padded with leading zeros.
10
* For example, if the value of the line number is 123, the last
11
* four characters of the string representation will be "0123".
12
*
13
* Note that there is a single space separating the closing
14
* parenthesis after the area code from the first digit of the
15
* prefix.
16
*/
17
@Override public String toString()
{
18
return String.format("(%03d) %03d-%04d",
19
areaCode, prefix, lineNumber);
20
}
如果你不打算指定格式,文档结构应该像这样:
1
/** *//**
2
* Returns a brief description of this potion. The exact details
3
* of the representation are unspecified and subject to change,
4
* but the following may be regarded as typical:
5
*
6
* "[Potion #9: type=love, smell=turpentine, look=india ink]"
7
*/
8
@Override public String toString()
{
}
在阅读了上面的文档后,编写代码的或者依赖详细格式维护数据的程序员将会在格式变化时开始抱怨。
不管你是否指定格式,需要toString来返回包含信息的值。
posted on 2008-07-01 21:31
一叶笑天 阅读(239)
评论(0) 编辑 收藏 所属分类:
JAVA技术