您的位置:首页 > 运维架构 > Apache

apache.commons.lang.builder 学习(一) ToStringBuilder

2017-01-23 00:00 661 查看
版本:commons-lang-2.4.jar

学习内容:apache.commons.lang.builder.ToStringBuilder

当你需要重载 toString 函数而不想写代码把当前类的所有成员信息列出来,可以用这个函数。

public class People {
private String name;
private int age;
private String sex;

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;
}

public String getSex() {
return sex;
}

public void setSex(String sex) {
this.sex = sex;
}
}

构造一个对象,sex不赋值,容易比较值为null的情况。

People people = new People();
people.setAge(18);
people.setName("小树");

System.out.println(people.toString());

如果不重写People类的toString()方法,控制台输出:test.People@2faadcc6

如果默认重写People类的toString()方法,控制台输出:People [name=小树, age=18, sex=null]

备注:默认重写的toString()方法是使用字符串拼接:"People [name=" + name + ", age=" + age + ", sex=" + sex + "]"。字符串用“+”拼接效率很低。

System.out.println(ToStringBuilder.reflectionToString(people));

控制台输出:test.People@2faadcc6[name=小树,age=18,sex=<null>]

System.out.println(ToStringBuilder.reflectionToString(people, ToStringStyle.DEFAULT_STYLE));

控制台输出:test.People@2faadcc6[name=小树,age=18,sex=<null>]

System.out.println(ToStringBuilder.reflectionToString(people, ToStringStyle.MULTI_LINE_STYLE));

控制台输出:test.People@2faadcc6[
name=小树
age=18
sex=<null>
]

System.out.println(ToStringBuilder.reflectionToString(people, ToStringStyle.NO_FIELD_NAMES_STYLE));

控制台输出:test.People@2faadcc6[小树,18,<null>]

System.out.println(ToStringBuilder.reflectionToString(people, ToStringStyle.SHORT_PREFIX_STYLE));

控制台输出:People[name=小树,age=18,sex=<null>]

System.out.println(ToStringBuilder.reflectionToString(people, ToStringStyle.SIMPLE_STYLE));

控制台输出:小树,18,<null>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息