工具类ToStringBuilder用法简介
ToStringBuilder在包 common-lang 中,主要用于一个类的格式化输出。ToStringBuilder类中的append方法可以向该类添加基本类型、数组和对象 ,只有添加的方法才会被toString方法输出。
ToStringStyle类则是对输出的内容进行格式化。
demo
1 import org.apache.commons.lang.builder.ToStringBuilder; 2 3 4 public class Person { 5 6 private String name; 7 private int sex; 8 private String addr; 9 10 public String getAddr() { 11 return addr; 12 } 13 public void setAddr(String addr) { 14 this.addr = addr; 15 } 16 public String getName() { 17 return name; 18 } 19 public void setName(String name) { 20 this.name = name; 21 } 22 public int getSex() { 23 return sex; 24 } 25 public void setSex(int sex) { 26 this.sex = sex; 27 } 28 29 @Override 30 public String toString(){ 31 return ToStringBuilder.reflectionToString(this,ToStringStyle.MULTI_LINE_STYLE); 32 } 33 }
tester
1 public class PersonTest { 2 3 /** 4 * @param args 5 */ 6 public static void main(String[] args) { 7 Person person = new Person(); 8 person.setName("watchdb"); 9 person.setSex(1); 10 person.setAddr("shanghai.zhangjiang"); 11 System.out.println(person.toString()); 12 13 } 14 15 }
ToStringStyle参数说明:
1. DEFAULT_STYLE
Person@fd13b5[name=watchdb,sex=1,addr=shanghai.zhangjiang]
2. MULTI_LINE_STYLE
Person@fd13b5[
name=watchdb
sex=1
addr=shanghai.zhangjiang
]
3. NO_FIELD_NAMES_STYLE
Person@fd13b5[watchdb,1,shanghai.zhangjiang]
4. SHORT_PREFIX_STYLE
Person[name=watchdb,sex=1,addr=shanghai.zhangjiang]
5. SIMPLE_STYLE
watchdb,1,shanghai.zhangjiang