这篇文章的目的:不介绍@Builder的原理,只说明它的使用效果。
@Builder
@ToString
public class People {
private Long id;
private String name;
private String address;
}
运行后(不要误会这段代码不能直接运行,要自己构建运行环境),查看对应的class文件发现People类变成了:
public class People {
private Long id;
private String name;
private String address;
People(final Long id, final String name, final String address) {
this.id = id;
this.name = name;
this.address = address;
}
public static PeopleBuilder builder() {
return new PeopleBuilder();
}
public String toString() {
return "People(id=" + this.id + ", name=" + this.name + ", address=" + this.address + ")";
}
public static class PeopleBuilder {
private Long id;
private String name;
private String address;
PeopleBuilder() {
}
public PeopleBuilder id(final Long id) {
this.id = id;
return this;
}
public PeopleBuilder name(final String name) {
this.name = name;
return this;
}
public PeopleBuilder address(final String address) {
this.address = address;
return this;
}
public People build() {
return new People(this.id, this.name, this.address);
}
public String toString() {
return "People.PeopleBuilder(id=" + this.id + ", name=" + this.name + ", address=" + this.address + ")";
}
}
}
所以可以这样使用:
@GetMapping("/hello")
public String hello() {
//等价与 new People(10L,"lihuo","888")
People people = People.builder().id(10L).name("lihuo").address("888").build();
System.out.println(people.toString());
return "Hello,World";
}
运行结果: