用Commons Lang ReflectionToStringBuilder or ToStringBuilder and ToStringBuilder创建toString() 方法
import org.apache.commons.lang.builder.ToStringBuilder; public void toString( ) { ReflectionToStringBuilder.toString( this ); }
public class Person { private String name; private String addr; private List<String> phone=new ArrayList<String>(); public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAddr() { return addr; } public void setAddr(String addr) { this.addr = addr; } public List<String> getPhone() { return phone; } public void setPhone(List<String> phone) { this.phone = phone; } @Override public String toString() { return ReflectionToStringBuilder.toString(this); }
public class ReflectionToStringBuilderTest { @Test public void testReflectionToStringBuilder(){ Person p=new Person(); List<String> list=new ArrayList<String>(); list.add("136"); list.add("151"); p.setName("lixueli"); p.setAddr("china"); p.setPhone(list); System.out.println(p.toString()); } }
@Override public String toString() { return ReflectionToStringBuilder.toString(this); }
输出为:com.lixueli.model.Person@1a0c10f[name=lixueli,addr=china,phone=[136, 151]]
@Override public String toString() { return new ToStringBuilder(this, ToStringStyle.MULTI_LINE_STYLE) .append("name", name) .append("addr", addr) .append("phone", phone) .toString( ); }
输出为:com.lixueli.model.Person@c7e553[
name=lixueli
addr=china
phone=[136, 151]
]
com.discursive.jccook.lang.builders. PoliticalCandidate@1cd2e5f[lastName=Jefferson,firstName=Thomas]
com.discursive.jccook.lang.builders.PoliticalCandidate@1cd2e5f[ lastName=Jefferson firstName=Thomas ]
com.discursive.jccook.lang.builders.PoliticalCandidate@1cd2e5f[Jefferson,Thomas]
Jefferson,Thomas