java lombok- @ Builder Notes
I. Introduction
In writing the code to be repeated write javaBean get, set, toString method is a no-tech and repeat things work, and more time to read, when javaBean class is also very complicated, lombok for annotations way, do not need to write these repeat code to make the code more simple and elegant.
Two, IDEA Add lombok
IDEA Add lombok link: IDEA plug-ins to add lombok
Three, @ Builder use Description
In no time using lombok @Builder notes:
User class needs to get, set methods for each field down, and the entire class looks code bloat.
UserInfo class: user add data objects to be repeated call set methods.
- User class needs to get, set methods for each field down, and the entire class looks code bloat.
public class User {
private String name;
private String comment;
private String sex;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getComment() {
return comment;
}
public void setComment(String comment) {
this.comment = comment;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
", comment='" + comment + '\'' +
", sex='" + sex + '\'' +
", age=" + age +
'}';
}
}
- UserInfo class: user add data objects to be repeated call set methods.
import java.util.ArrayList;
import java.util.List;
public class UserInfo {
public static void main(String[] args) {
printUser();
}
private static void printUser() {
List<User> users = new ArrayList<>();
//user对象添加属性值
User user = new User();
user.setName("李明");
user.setAge(14);
user.setSex("男");
user.setComment("喜欢读书");
//user对象添加到list集合
users.add(user);
System.out.println("User infomation::" + users);
}
}
Notes lombok way of writing:
User class do not need to write get, set method, the code is very simple and elegant
UserInfo class can be constructed using the Builder directly User class object and set property values
- User class do not need to write get, set method, the code is very simple and elegant
import lombok.Builder;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
@Getter
@Setter
@ToString
@Builder
public class User {
private String name;
private String comment;
private String sex;
private int age;
}
- UserInfo class can be constructed using the Builder directly User class object and set property values
import java.util.ArrayList;
import java.util.List;
public class UserInfo {
public static void main(String[] args) {
printUser();
}
private static void printUser() {
List<User> users = new ArrayList<>();
//user对象添加属性值
User user = User.builder()
.name("李明")
.age(16)
.sex("男")
.comment("喜欢读书")
.build();
//user对象添加到list集合
users.add(user);
System.out.println("User infomation::" + users);
}
}
- Output
User infomation::[User(name=李明, comment=喜欢读书, sex=男, age=16)]