标签:lan lin www hone scons origin access ann 方法体
比如一个简单的Person类,用常规的写法:
public class Person {
private String name;
private String address;
private Integer age;
private String hobbit;
private String phone;
public Person() {
}
public Person(String name, String address, Integer age, String hobbit, String phone) {
this.name = name;
this.address = address;
this.age = age;
this.hobbit = hobbit;
this.phone = phone;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getHobbit() {
return hobbit;
}
public void setHobbit(String hobbit) {
this.hobbit = hobbit;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
@Override
public String toString() {
return "Person{" +
"name=‘" + name + ‘\‘‘ +
", address=‘" + address + ‘\‘‘ +
", age=" + age +
", hobbit=‘" + hobbit + ‘\‘‘ +
", phone=‘" + phone + ‘\‘‘ +
‘}‘;
}
}
我不明白的地方在于写这种空白的set和get有什么意思 那还不如直接用public
用@Data的写法:
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Person {
private String name;
private String address;
private Integer age;
private String hobbit;
private String phone;
}
自动生成相关的方法:
Accessors翻译是存取器。通过该注解可以控制getter和setter方法的形式。
使用fluent属性,getter和setter方法的方法名都是属性名,且setter方法返回当前对象
@Data
@Accessors(fluent = true)
class User {
private Integer id;
private String name;
// 生成的getter和setter方法如下,方法体略
public Integer id(){}
public User id(Integer id){}
public String name(){}
public User name(String name){}
}
使用chain属性,setter方法返回当前对象
@Data
@Accessors(chain = true)
class User {
private Integer id;
private String name;
// 生成的setter方法如下,方法体略
public User setId(Integer id){}
public User setName(String name){}
}
使用prefix属性,getter和setter方法会忽视属性名的指定前缀(遵守驼峰命名)
@Data
@Accessors(prefix = "f")
class User {
private Integer fId;
private String fName;
// 生成的getter和setter方法如下,方法体略
public Integer id(){}
public void id(Integer id){}
public String name(){}
public void name(String name){}
标签:lan lin www hone scons origin access ann 方法体
原文地址:https://www.cnblogs.com/ying568353087/p/13140724.html