简介
- @Accessors 访问器 在lombok v0.11.0版本引入.
- @Accessors注释用于配置lombok如何生成和查找getter和setter。
- @Accessors有三个选项
- fluent 为true时, 省略set/get方法关键字, 并且set方法返回对象本身。
- chain 为true时,set方法返回对象本身。
- prefix 为true时,省略配置的属性名前缀
具体实现
fluent
省略set/get方法关键字, 并且set方法返回对象本身
- 实体类 UserFluent.java
@Getter
@Setter
@Accessors(fluent = true)
public class UserFluent {
private String name;
private Integer age;
}
- 编译类 UserFluent.class
public class UserFluent {
private String name;
private Integer age;
public UserFluent() {
}
public String name() {
return this.name;
}
public Integer age() {
return this.age;
}
public UserFluent name(final String name) {
this.name = name;
return this;
}
public UserFluent age(final Integer age) {
this.age = age;
return this;
}
}
- 测试类
@Slf4j
public class UserFluentTest {
public static void main(String[] args) {
UserFluent userFluent = new UserFluent();
userFluent.name("常山赵子龙").age(19);
log.info("name : {}, userFluent = {} " , userFluent.name(), userFluent.age());
}
}
- 执行结果
name : 常山赵子龙, age= 19
chain
链式setter, set方法返回对象本身
@Getter
@Setter
@Accessors(chain = true)
public class UserChain {
private String name;
private Integer age;
}
编译结果UserChain.class
public class UserChain {
private String name;
private Integer age;
public UserChain() {
}
public String getName() {
return this.name;
}
public Integer getAge() {
return this.age;
}
public UserChain setName(final String name) {
this.name = name;
return this;
}
public UserChain setAge(final Integer age) {
this.age = age;
return this;
}
}
- 测试类
@Slf4j
public class UserChainTest {
public static void main(String[] args) {
UserChain userChain = new UserChain().setName("常山赵子龙").setAge(19);
log.info("name: {}, age = {} " , userChain.getName(), userChain.getAge());
}
}
- 执行结果
name : 常山赵子龙, age : 19
prefix
get/set方法省略配置的属性名前缀
- 实体类
@Getter
@Setter
@Accessors(prefix = "u")
public class UserPrefix {
private String uName;
private Integer uAge;
}
- 编译类
public class UserPrefix {
private String uName;
private Integer uAge;
public UserPrefix() {
}
public String getName() {
return this.uName;
}
public Integer getAge() {
return this.uAge;
}
public void setName(final String uName) {
this.uName = uName;
}
public void setAge(final Integer uAge) {
this.uAge = uAge;
}
}
- 测试类
@Slf4j
public class UserPrefixTest {
public static void main(String[] args) {
UserPrefix userPrefix = new UserPrefix();
userPrefix.setName("常山赵子龙");
userPrefix.setAge(19);
log.info("name : {}, age : {}" , userPrefix.getName(), userPrefix.getAge());
}
}
- 执行结果
name : 常山赵子龙, age : 19