[英]Why does ToStringBuilder work inconsistently?
In the following code, why do the two lines containing System.out.println(person);
在下面的代码中,为什么两行包含
System.out.println(person);
yield different outputs? 产生不同的输出? The second line indirectly calls the method
Job.toString
yielding the string "Manager"
, but the first line mysteriously does not yielding Job@28f67ac7
. 第二行间接调用
Job.toString
方法,产生字符串"Manager"
,但是第一行神秘地不产生Job@28f67ac7
。 The line in between person.put("a", "b");
person.put("a", "b");
之间的行person.put("a", "b");
doesn't seem to me like it should make any difference. 在我看来,这似乎没有什么不同。
Code: 码:
import java.util.*;
import org.apache.commons.lang3.builder.*;
class Job extends HashMap<String, String> {
@Override public String toString() {
return "Manager";
}
}
class Person extends HashMap<String, String> {
Job job;
Person() {
this.job = new Job();
}
@Override public String toString() {
return ToStringBuilder.reflectionToString(this);
}
}
class Test {
public static void main(String[] args) {
Person person = new Person();
System.out.println(person);
person.put("a", "b");
System.out.println(person);
}
}
Console: 安慰:
Person@2b80d80f[job=Job@28f67ac7,threshold=0,loadFactor=0.75]
Person@2b80d80f[job=Manager,threshold=12,loadFactor=0.75]
2 things contribute to the output changing: 有两点有助于改变输出:
new Person().equals(new Job()) == true
new Person().equals(new Job()) == true
This means while person and person.job in your example remain equal to each other, ToStringBuilder will not call person.job.toString(), but when the map contents change, person.job.toString() will be called. 这意味着在您的示例中person和person.job彼此相等时,ToStringBuilder不会调用person.job.toString(),但是当地图内容更改时,将调用person.job.toString()。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.