全部博文(36)
分类: Java
2013-02-05 13:12:38
比如说我们需要打印某个方法的User参数对象
package test;
/**
*
* @author zhengtian
* @time 2012-6-28
*/
public class User {
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
下面是ToStringBuilder的使用方法
System.out.println("-------------ToStringBuilder-------------------------");
User u = new User();
u.setAge(25);
u.setName("zhengtian");
//对象及其属性一行显示
System.out.println(ToStringBuilder.reflectionToString(u));
System.out.println(ToStringBuilder.reflectionToString(u, ToStringStyle.DEFAULT_STYLE));
//属性换行显示
System.out.println(ToStringBuilder.reflectionToString(u, ToStringStyle.MULTI_LINE_STYLE));
//不显示属性名,只显示属性值,在同一行显示
System.out.println(ToStringBuilder.reflectionToString(u, ToStringStyle.NO_FIELD_NAMES_STYLE));
//对象名称简写
System.out.println(ToStringBuilder.reflectionToString(u, ToStringStyle.SHORT_PREFIX_STYLE));
//只显示属性
System.out.println(ToStringBuilder.reflectionToString(u, ToStringStyle.SIMPLE_STYLE));
结果显示:
-------------ToStringBuilder-------------------------
test.User@141d683[name=zhengtian,age=25]
test.User@141d683[name=zhengtian,age=25]
test.User@141d683[
name=zhengtian
age=25
]
test.User@141d683[zhengtian,25]
User[name=zhengtian,age=25]
zhengtian,25
描述:ToStringBuilder比较适合在打日志时,输出参数的信息,特别是在参数为对象时,该工具类能够很方便的自动打印对象中的属性值。