【每天学个新注解】Day 10 Lombok注解简解(九)—@Accessors

在之前的几天,我们系统学习了Lombok的常见注解,并且将其官网stable中的所有注解都讲解了一编,接下来会通过两到三天的时间将Lombok目前正在试验的(experimental)注解简单过一遍,以下为experimental状态的所有注解。
在这里插入图片描述

@Accessors

@Accessors注解用于配置生成的getter和setter方法的访问级别和命名方式
接下来介绍的很多Lombok注解都不建议使用,因为Lombok后续增加的很多注解都与其设计初衷相违背,具体的使用建议我会在Lombok注解讲解的最后根据我的使用经验简单讲一下

1、如何使用

  • 注解在需要控制Getter、Setter方法访问级别和命名方式的地方(为@Getter、@Setter提供升级版功能)。
  • @Accessors可以使用以下属性进行配置:
    chain:boolean类型,默认为false。如果设置为true,则生成的setter方法返回this,以支持链式调用。
    fluent:boolean类型,默认为false。如果设置为true,则生成的getter和setter方法的方法名不带get和set前缀。
    prefix:String类型,默认为空字符串。设置生成的getter和setter方法的前缀。
    使用@Accessors可以在类级别和属性级别进行配置。在类级别配置时,会为该类中的所有属性生成相同的访问级别和命名方式。在属性级别配置时,可以为每个属性单独指定不同的配置。

2、代码示例

例:

@ToString
@Getter
@Setter
@Accessors(chain = true, fluent = true, prefix = "my")
public class AccessorsExample {
    private String myName;
    private int myAge;

    public static void main(String[] args) {
        AccessorsExample example = new AccessorsExample().name("John").age(30);
        System.out.printf("Age" + example.age());
    }
}

编译后:在上面的示例中,我们在类级别使用@Accessors注解配置了链式调用、去除前缀的属性。因此,我们可以通过链式调用的方式设置属性的值,并且生成的getter和setter方法的方法名不带get和set前缀。在Main方法中,我们创建了一个对象,并使用生成的setter方法设置属性的值。最后,打印该对象的age属性时,也没有指定是通过getter方法获取属性值。

public class AccessorsExample {
    private String myName;
    private int myAge;

    public AccessorsExample() {
    }

    public static void main(String[] args) {
        AccessorsExample example = (new AccessorsExample()).name("John").age(30);
        System.out.printf("Age" + example.age());
    }

    @Generated
    public String toString() {
        return "AccessorsExample(myName=" + this.name() + ", myAge=" + this.age() + ")";
    }

    @Generated
    public String name() {
        return this.myName;
    }

    @Generated
    public int age() {
        return this.myAge;
    }

    @Generated
    public AccessorsExample name(String myName) {
        this.myName = myName;
        return this;
    }

    @Generated
    public AccessorsExample age(int myAge) {
        this.myAge = myAge;
        return this;
    }
}

运行结果:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值